frequency of letters in column python

痞子三分冷 提交于 2019-12-02 00:42:15

As with my answer to your last question, you should wrap your functionality in a function:

def lettercount(pos):
    return {c: pos.count(c) for c in pos}

Then you can easily apply it to the tuples from zip:

counts = [lettercount(t) for t in zip(seq1, seq2, seq3)]

Or combine it into the existing loop:

...
counts = []
for position in zip(seq1, seq2, seq3): # sets at same position
    counts.append(lettercount(position))
    for pair in combinations(position, 2): # pairs within set
        ...

Here:

sequences = ['AATC',
             'GCCT',
             'ATCA']
f = zip(*sequences)
counts = [{letter: column.count(letter) for letter in column} for column in f]
print(counts)

Output (reformatted):

[{'A': 2, 'G': 1}, 
 {'A': 1, 'C': 1, 'T': 1}, 
 {'C': 2, 'T': 1}, 
 {'A': 1, 'C': 1, 'T': 1}]

Salient features:

  • Rather than explicitly naming seq1, seq2, etc., we put them into a list.
  • We unpack the list with the * operator.
  • We use a dict comprehension inside a list comprehension to generate the counts for each letter in each column. It's basically what you did for the one-sequence case, but more readable (IMO).
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!