将字典值的位置解析到列表中 [英] Parse positions of dictionary values into a list
问题描述
假设您有一本具有以下数据类型的字典:
Let's say you have a dictionary with the following type of data:
{'abc':'AGCTAC', 'def': 'AGGTAC', 'ghi':'AGGTAG'}
我希望能够运行一个显示每个位置值的函数,例如
I want to be able to run a function that shows the values at each position, e.g.
(('A','A','A'),('G','G','G'),('C','G','G'))
然后可以运行一个计数器,如人们建议使用Collection Counter的计数器.
And then be able to run a counter such as people have suggested with collections Counter.
推荐答案
>>> 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')]
请记住,字典是无序的,因此元组中的元素可能以不同的顺序出现.但是,所有元组的顺序都相同
Remember that dicts are unordered, so the elements in the tuples may occur in a different order. However the order will be the same for all the tuples
在Python3中,zip返回一个"zip对象",因此您需要在其周围包裹tuple()
In Python3, zip returns a "zip object" so you need to wrap tuple()
around it
>>> tuple(zip(*d.values()))
(('A', 'A', 'A'), ('G', 'G', 'G'), ('C', 'G', 'G'), ('T', 'T', 'T'), ('A', 'A', 'A'), ('C', 'G', 'C'))
如果不需要中间元组,只需传递给Counter
If you don't need the intermediate tuple, just pass to 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})
这篇关于将字典值的位置解析到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!