python - 遍历元组以计算列表中的值

标签 python tuples

我有一个包含多个基因的字典。 tuple(zip()) 给出了每个位点的核苷酸。例如。 (A, A, A), (T, T, G), 等等。我正在尝试计算每个位点的核苷酸数量。这样站点 1 显示 3 个 A,站点 2 显示 2 个 T 和 1 个 G。当我运行我的代码时,它只添加到 A,没有其他任何内容。

List = tuple(zip(*myDict.values()))

A = 0
T = 0
G = 0
C = 0

site = 0

for value in List:
    site +=1
    if 'A':
        A += 1
    elif 'T':
        T += 1
    elif 'G':
        G += 1
    else:
        C =+ 1

print 'Site:', site
print 'A:', A
print 'T:', T
print 'G:', G
print 'C:', C

最佳答案

您可以(再一次)最好地使用 collections.Counter():

[Counter(site) for site in zip(*myDict.values())]

这将创建每个站点的基因计数列表。

演示:

>>> from collections import Counter
>>> myDict = {'abc':'AGCTAC', 'def': 'AGGTAC', 'ghi':'AGGTAG'}
>>> result = [Counter(site) for site in zip(*myDict.values())]
>>> result
[Counter({'A': 3}), Counter({'G': 3}), Counter({'G': 2, 'C': 1}), Counter({'T': 3}), Counter({'A': 3}), Counter({'C': 2, 'G': 1})]
>>> result[0]  # genes at site 0
Counter({'A': 3})
>>> result[2]  # genes at site 2
Counter({'G': 2, 'C': 1})

关于python - 遍历元组以计算列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12642929/

相关文章:

sorting - 如何在Julia中按给定元素对元组进行排序?

python - Python 中的元组减法语句

python - Pandas Dataframe 到元组字典

Python:搜索 dict 的值来查找正则表达式

Python 截断方法大小参数行为

python - 如何在python中格式化字符串的一部分?

c# - Tuple.Create 返回类型

python - 用于一次性可迭代的列表或元组

python - 如何对连续音频进行分类

python - 如何更改 PIP 以使用 Python 2.7