[英]Convert a list of tuples to a dictionary, based on tuple values
I have a little problem, maybe dumb, but it seems I can't solve it.我有一个小问题,也许很愚蠢,但似乎我无法解决。
I have a list of objects that have members, but let's say my list is this:我有一个包含成员的对象列表,但假设我的列表是这样的:
l = [(1, 'a'), (2, 'a'), (1, 'b'), (1, 'c'), (3, 'a')]
I want to "gather" all elements based on the value I choose, and to put them into a dictionary based on that value/key (can be both the first or the second value of the tuple).我想根据我选择的值“收集”所有元素,并根据该值/键(可以是元组的第一个或第二个值)将它们放入字典中。
For example, if I want to gather the values based on the first element, I want something like that:例如,如果我想根据第一个元素收集值,我想要这样的东西:
{1: [(1, 'a'), (1, 'b'), (1, 'c')], 2: [(2, 'a')], 3: [(3, 'a')]}
However, what I achieved until now is this:但是,到目前为止,我取得的成就是:
>>> {k:v for k,v in zip([e[0] for e in l], l)}
{1: (1, 'c'), 2: (2, 'a'), 3: (3, 'a')}
Can somebody please help me out?有人可以帮我吗?
My first thought would be using defaultdict(list)
(efficient, in linear time), which does exactly what you were trying to do:我的第一个想法是使用
defaultdict(list)
(高效,线性时间),这正是你想要做的:
from collections import defaultdict
dic = defaultdict(list)
l = [(1, 'a'), (2, 'a'), (1, 'b'), (1, 'c'), (3, 'a')]
for item in l:
dic[item[0]].append(item)
output output
defaultdict(list,{1: [(1, 'a'), (1, 'b'), (1, 'c')], 2: [(2, 'a')], 3: [(3, 'a')]})
Here with list comprehension, oneliner:这里有列表理解,oneliner:
l = [(1, 'a'), (2, 'a'), (1, 'b'), (1, 'c'), (3, 'a')]
print (dict([(x[0], [y for y in l if y[0] == x[0]]) for x in l]))
Output: Output:
{1: [(1, 'a'), (1, 'b'), (1, 'c')], 2: [(2, 'a')], 3: [(3, 'a')]}
Here you go:这里是 go:
l = [(1, 'a'), (2, 'a'), (1, 'b'), (1, 'c'), (3, 'a')]
output_dict = dict()
for item in l:
if item[0] in output_dict:
output_dict[item[0]].append(item)
continue
output_dict[item[0]] = [item]
print(output_dict)
First create a dico with list inside:首先创建一个带有列表的dico:
l = [(1, 'a'), (2, 'a'), (1, 'b'), (1, 'c'), (3, 'a')]
dico={}
for i in range(4):
dico[i]=[]
Then fill this dico然后填充这个dico
for i in l:
dico[i[0]].append(i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.