merge nested list by first value in each list in python(按python中每个列表中的第一个值合并嵌套列表)
问题描述
我有此代码的一个版本,但它似乎过于复杂.这是我卡住的简化版本.在python3中.
I have a version of this code working but it seems overly complex. This is the simplified version im getting stuck on. in python3.
list1 = [['a', 'b'], ['a', 'c'], ['a', 't'], ['x', 'f'], ['x', 'g'], ['d', 'z']]
z = len(list1)
for i in range(0, z):
for j in range(i + 1, z):
while list1[i][0] == list1[j][0]:
list1[i] = list1[i] + [list1[j][-1]]
if list1[j] in list1:
list1.remove(list1[j])
z = z - 1
我想要输出.
[['a', 'b', 'c', 't'], ['x', 'f', 'g'], ['d', 'z']]
推荐答案
修改 Darryl 的一点:
Modding Darryl's a bit:
d = {}
for head, *tail in lst:
d.setdefault(head, [head]).extend(tail)
lst2 = list(d.values())
这篇关于按python中每个列表中的第一个值合并嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!