merge nested list by first value in each list in python

流过昼夜 提交于 2021-02-05 12:30:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!