通过python中每个列表中的第一个值合并嵌套列表 [英] merge nested list by first value in each list in python

查看:27
本文介绍了通过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中每个列表中的第一个值合并嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆