Joh*_*son 3 python dictionary python-2.7
我有一个像这样的元组列表:
[('id1', 'text1', 0, 'info1'),
('id2', 'text2', 1, 'info2'),
('id3', 'text3', 1, 'info3'),
('id1', 'text4', 0, 'info4'),
('id4', 'text5', 1, 'info5'),
('id3', 'text6', 0, 'info6')]
Run Code Online (Sandbox Code Playgroud)
我想将它转换为dict,将id作为键和所有其他值保存为元组列表,扩展那些存在的元素:
{'id1': [('text1', 0, 'info1'),
('text4', 0, 'info4')],
'id2': [('text2', 1, 'info2')],
'id3': [('text3', 1, 'info3'),
('text6', 0, 'info6')],
'id4': [('text5', 1, 'info5')]}
Run Code Online (Sandbox Code Playgroud)
现在我使用非常简单的代码:
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]))
Run Code Online (Sandbox Code Playgroud)
我相信应该有更优雅的方式来实现相同的结果,可能有发电机.有任何想法吗?
对于这类问题,在字典内附加列表的有用功能是 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:])
Run Code Online (Sandbox Code Playgroud)
结果:
{'id1': [('text1', 0, 'info1'), ('text4', 0, 'info4')],
'id2': [('text2', 1, 'info2')],
'id3': [('text3', 1, 'info3'), ('text6', 0, 'info6')],
'id4': [('text5', 1, 'info5')]}
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用collections.defaultdict:
from collections import defaultdict
x = defaultdict(list)
for tup in data:
x[tup[0]].append(tup[1:])
Run Code Online (Sandbox Code Playgroud)
这有类似的结果.
| 归档时间: |
|
| 查看次数: |
487 次 |
| 最近记录: |