将字典值的位置解析为列表

0 python dictionary list

假设您有一个包含以下数据类型的字典:

{'abc':'AGCTAC', 'def': 'AGGTAC', 'ghi':'AGGTAG'}
Run Code Online (Sandbox Code Playgroud)

我希望能够运行一个显示每个位置值的函数,例如

(('A','A','A'),('G','G','G'),('C','G','G'))
Run Code Online (Sandbox Code Playgroud)

然后能够运行一个计数器,如人们建议使用集合计数器.

Joh*_*ooy 5

>>> d = {'abc':'AGCTAC', 'def': 'AGGTAC', 'ghi':'AGGTAG'}
>>> zip(*d.values())
[('A', 'A', 'A'), ('G', 'G', 'G'), ('C', 'G', 'G'), ('T', 'T', 'T'), ('A', 'A', 'A'), ('C', 'G', 'C')]
Run Code Online (Sandbox Code Playgroud)

请记住,dicts是无序的,因此元组中的元素可能以不同的顺序出现.但是,所有元组的顺序都是相同的

在Python3中,zip返回一个"zip对象",因此您需要将其tuple()环绕

>>> tuple(zip(*d.values()))
(('A', 'A', 'A'), ('G', 'G', 'G'), ('C', 'G', 'G'), ('T', 'T', 'T'), ('A', 'A', 'A'), ('C', 'G', 'C'))
Run Code Online (Sandbox Code Playgroud)

如果你不需要中间元组,只需传递给 Counter

>>> from collections import Counter
>>> Counter(zip(*d.values()))
Counter({('A', 'A', 'A'): 2, ('C', 'G', 'G'): 1, ('G', 'G', 'G'): 1, ('T', 'T', 'T'): 1, ('C', 'G', 'C'): 1})
Run Code Online (Sandbox Code Playgroud)