简体   繁体   English

计算python中列表的每个序列中元素的出现

[英]counting occurrence of elements in each sequence of the list in python

I have a (very big) list like the small example. 我有一个(非常大的)清单,就像小例子一样。 I want to count the number of D in each sequence in the list and divide by the length of that sequence. 我想计算列表中每个序列的D数,然后除以该序列的长度。 (occurrence of D in each sequence). (每个序列中D的出现)。

small example: 小例子:

l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQNDDVKLSAE']

do you guys know how to do that? 你们知道怎么做吗?

You can simply use a list comprehension , get the count of D in each sequence and divide by the length of the sequence: 您可以简单地使用列表推导 ,获取每个序列中D的数量,然后除以序列的长度:

l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQNDDVKLSAE']

result = [x.count('D')/len(x) for x in l]
print(result)
# [0.07692307692307693, 0.125, 0.125, 0.21428571428571427, 0.17647058823529413]

To handle zero length sequences and avoid ZeroDivisionError , you may use a ternary operator : 要处理零长度的序列并避免ZeroDivisionError ,可以使用三元运算符

result = [(x.count('D')/len(x) if x else 0) for x in l]

You can use list comprehension in order to get the expected result. 您可以使用列表推导来获得预期的结果。

I have iterated over each item in the list, for each one of the items in the list I've counted the number of the occurrences of the specified sub string (in this case 'D'). 我遍历了列表中的每个项目,对于列表中的每个项目,我已经计算了指定子字符串(在本例中为“ D”)的出现次数。

Last, I've divided the number of the occurrences with the length of the item. 最后,我将出现的次数除以项目的长度。

l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQNDDVKLSAE']
output = [float(item.count("D")) / float(len(item)) for item in l]

You're looking for something like: 您正在寻找类似的东西:

def fn(x):
    return x.count('D') / len(x)
results = ap(fn, l)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM