按python中每个列表中的第一个值合并嵌套列表

use*_*569 -2 python nested list

我有此代码的一个版本,但它似乎过于复杂。这是我卡住的简化版本。在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
Run Code Online (Sandbox Code Playgroud)

我要输出。

[['a', 'b', 'c', 't'], ['x', 'f', 'g'], ['d', 'z']]
Run Code Online (Sandbox Code Playgroud)

Kel*_*ndy 5

修改 Darryl 有点:

d = {}
for head, *tail in lst:
    d.setdefault(head, [head]).extend(tail)

lst2 = list(d.values())
Run Code Online (Sandbox Code Playgroud)