python - 在循环中将计数器增加为字典值

标签 python loops

我有一个名为 aa_seq 的数百个氨基酸序列的列表,它看起来像这样:['AFYIVHPMFSELINFQNEGHECQCQCG', 'KVHSLPGMSDNGSPAVLPKTEFNKYKI', 'RAQVEDLMSLSPHVENASIPKGSTPIP', 'TSTNNYPMVQEQAILSCIEQTMVADAK',...]。 每个序列有 27 个字母长。我必须确定每个位置 (1-27) 最常用的氨基酸及其使用频率。

到目前为止我有:

   count_dict = {} 
   counter = count_dict.values()
   aa_list = ['A', 'C', 'D', 'E' ,'F' ,'G' ,'H' ,'I' ,'K' ,'L' ,    #one-letter code for amino acids
       'M' ,'N' ,'P' ,'Q' ,'R' ,'S' ,'T' ,'V' ,'W' ,'Y']
   for p in range(0,26):                       #first round:looks at the first position in each sequence
        for s in range(0,len(aa_seq)):          #goes through all sequences of the list 
             for item in aa_list:                #and checks for the occurrence of each amino acid letter (=item)
                  if item in aa_seq[s][p]:
                      count_dict[item]            #if that letter occurs at the respective position, make it a key in the dictionary
                      counter += 1                #and increase its counter (the value, as definded above) by one 
    print count_dict

它说 KeyError: 'A',它指向行 count_dict[item]。所以 aa_list 的项目显然不能以这种方式添加为键..?我怎么做?并且它还给出了关于计数器的错误“'int'对象不可迭代”。还可以如何增加计数器?

最佳答案

您可以使用 Counter

>>> from collections import Counter

>>> l = ['AFYIVHPMFSELINFQNEGHECQCQCG', 'KVHSLPGMSDNGSPAVLPKTEFNKYKI', 'RAQVEDLMSLSPHVENASIPKGSTPIP', 'TSTNNYPMVQEQAILSCIEQTMVADAK']
>>> s = [Counter([l[j][i] for j in range(len(l))]).most_common()[0] for i in range(27)]
>>> s
[('A', 1),
 ('A', 1),
 ('Y', 1),
 ('I', 1),
 ('N', 1),
 ('Y', 1),
 ('P', 2),
 ('M', 4),
 ('S', 2),
 ('Q', 1),
 ('E', 2),
 ('Q', 1),
 ('I', 1),
 ('I', 1),
 ('A', 1),
 ('Q', 1),
 ('A', 1),
 ('I', 1),
 ('I', 1),
 ('Q', 1),
 ('E', 2),
 ('C', 1),
 ('Q', 1),
 ('A', 1),
 ('Q', 1),
 ('I', 1),
 ('I', 1)]

但是,如果您有大量数据集,我可能会变得效率低下。

关于python - 在循环中将计数器增加为字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43311964/

相关文章:

python - Matplotlib line2d plot set_data 不工作

python - 如何用 Pandas 数据框中的列值替换单元格中的索引值

java - 找不到无限循环的原因

c# - 如何检查拆分容器内的所有文本框?

python - Python 的 MySQL 查询中字符串参数不足,多个 IN 子句包含列表值

python - 扩展用户模型 Django 2.0

Python:猴子修补函数的源代码

loops - 如果永远运行,ticker.C 是否会泄漏内存?

python - 将元素分配给列表中的列表

javascript - 如何让这个定时器循环起来? JS