Python将每个字符串除以字符串的总长度

时间:2018-12-10 21:19:15

标签: python function for-loop return jupyter-notebook

感谢您的帮助和耐心。

我是python的新手,正在尝试计算特定原子符号出现的次数除以原子总数。因此该函数接受字符串列表作为参数,并返回包含'C','H','O'和'N'的分数的列表。但是我不断获得一个结果,而不是为每个原子获得全部。我的尝试如下:

Atoms = ['N', 'C', 'C', 'O', 'H', 'H', 'C', 'H', 'H', 'H', 'H', 'O', 'H']

def count_atoms (atoms):
    for a in atoms:
        total = atoms.count(a)/len(atoms)
        return total

然后

faa = count_atoms(atoms)
print(faa)

但是我只得到一个结果,即0.07692307692307693。我应该得到一个以[0.23076923076923078,.. etc]开头的列表,但我不知道该怎么做。我应该使用for循环和return语句计算分子中'C','H','O'和'N'原子符号的分数。 :(请帮助,将不胜感激。

4 个答案:

答案 0 :(得分:1)

@ganderson注释解释了该问题。关于替代实现,这里是使用collections.Counter

from collections import Counter

atoms = ['N', 'C', 'C', 'O', 'H', 'H', 'C', 'H', 'H', 'H', 'H', 'O', 'H']

def count_atoms(atoms):
    num = len(atoms)
    return {atom:count/num for atom, count in Counter(atoms).items()}

print(count_atoms(atoms))

答案 1 :(得分:0)

好吧,您在第一个循环中返回变量total。为什么不使用列表存储值?像这样:

atoms = ['N', 'C', 'C', 'O', 'H', 'H', 'C', 'H', 'H', 'H', 'H', 'O', 'H'] #python is case sensitive!

def count_atoms (atoms):
    return_list = [] #empty list
    for a in atoms:
        total = atoms.count(a)/len(atoms)
        return_list.append(total) #we add a new item
    return return_list #we return everything and leave the function

答案 2 :(得分:0)

最好返回字典,这样您就知道分数对应于哪个元素:

>>> fractions = {element: Atoms.count(element)/len(Atoms) for element in Atoms}
>>> fractions
{'N': 0.07692307692307693, 'C': 0.23076923076923078, 'O': 0.15384615384615385, 'H': 0.5384615384615384}

然后,您甚至可以查找特定元素的分数,例如:

>>> fractions['N']
0.07692307692307693

但是,如果必须使用for循环和return语句,那么@ not_a_bot_no_really_82353的答案将是正确的。

答案 3 :(得分:0)

一个简单的班轮应该做

[atoms.count(a)/float(len(atoms)) for a in set(atoms)]

或者更好地使用理解力来创建字典

{a:atoms.count(a)/float(len(atoms)) for a in set(atoms)}

输出

{'C': 0.23076923076923078,
 'H': 0.5384615384615384,
 'N': 0.07692307692307693,
 'O': 0.15384615384615385}

如果您仍然想使用for循环。我建议选择map,这样会更清洁

atoms = ['N', 'C', 'C', 'O', 'H', 'H', 'C', 'H', 'H', 'H', 'H', 'O', 'H'] 

def count_atoms (a):
    total = atoms.count(a)/float(len(atoms))
    return total

map(count_atoms,atoms)