问题
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
I want output.
[['a', 'b', 'c', 't'], ['x', 'f', 'g'], ['d', 'z']]
回答1:
Modding Darryl's a bit:
d = {}
for head, *tail in lst:
d.setdefault(head, [head]).extend(tail)
lst2 = list(d.values())
回答2:
A simplfied construction is the following two steps.
d = {}
for sublist in lst:
d.setdefault(sublist[0], []).extend(sublist[1:])
lst2 = [[k] + v for k, v in d.items()]
print(lst2)
>>> [['a', 'b', 'c', 't'], ['x', 'f', 'g'], ['d', 'z']]
Explanation
(1) Dictionary d places items with the same first element as a dictionary key, with values corresponding to the remaining elements to produce:
{'a': ['b', 'c', 't'], 'x': ['f', 'g'], 'd': ['z']}
(2) Next, the list comprehension uses the key of each dictionary entry as the first element of a sublist and the value of the items as the remaining elements to produce the desired result
来源:https://stackoverflow.com/questions/60012337/merge-nested-list-by-first-value-in-each-list-in-python