小编Joh*_*son的帖子

使用元组中的唯一键和各种列表值创建一个dict

我有一个像这样的元组列表:

[('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)

我相信应该有更优雅的方式来实现相同的结果,可能有发电机.有任何想法吗?

python dictionary python-2.7

3
推荐指数
1
解决办法
487
查看次数

标签 统计

dictionary ×1

python ×1

python-2.7 ×1