我有一个像这样的元组列表:
[('id1', 'text1', 0, 'info1'),
('id2', 'text2', 1, 'info2'),
('id3', 'text3', 1, 'info3'),
('id1', 'text4', 0, 'info4'),
('id4', 'text5', 1, 'info5'),
('id3', 'text6', 0, 'info6')]
我想将其转换为 dict,将 ids 保留为键,将所有其他值保留为元组列表,扩展存在的那些:
{'id1': [('text1', 0, 'info1'),
('text4', 0, 'info4')],
'id2': [('text2', 1, 'info2')],
'id3': [('text3', 1, 'info3'),
('text6', 0, 'info6')],
'id4': [('text5', 1, 'info5')]}
现在我使用非常简单的代码:
for x in list:
if x[0] not in list: list[x[0]] = [(x[1], x[2], x[3])]
else: list[x[0]].append((x[1], x[2], x[3]))
我相信应该有更优雅的方式来实现相同的结果,也许使用生成器。有任何想法吗?
最佳答案
dict.setdefault 是将这类问题附加到包含在字典中的列表的一种有用方法。您可以使用它从字典中检索现有列表,或者在缺少时添加一个空列表,如下所示:
data = [('id1', 'text1', 0, 'info1'),
('id2', 'text2', 1, 'info2'),
('id3', 'text3', 1, 'info3'),
('id1', 'text4', 0, 'info4'),
('id4', 'text5', 1, 'info5'),
('id3', 'text6', 0, 'info6')]
x = {}
for tup in data:
x.setdefault(tup[0], []).append(tup[1:])
结果:{'id1': [('text1', 0, 'info1'), ('text4', 0, 'info4')],
'id2': [('text2', 1, 'info2')],
'id3': [('text3', 1, 'info3'), ('text6', 0, 'info6')],
'id4': [('text5', 1, 'info5')]}
我实际上发现 setdefault
方法使用起来有点尴尬(还有一些人 agree ),并且总是忘记它是如何工作的。我通常使用 collections.defaultdict 代替:from collections import defaultdict
x = defaultdict(list)
for tup in data:
x[tup[0]].append(tup[1:])
这有类似的结果。关于python - 创建一个具有唯一键和来自元组的各种列表值的字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31490101/