Python:合并嵌套列表

发布于 2024-12-10 16:18:45 字数 394 浏览 5 评论 0原文

初学者在这里。

我有 2 个要合并的嵌套列表:

list1 = ['a',
         (b, c),
         (d, e),
         (f, g, h) ]

list2 = [(p,q),
         (r, s),
         (t),
         (u, v, w) ]

我正在寻找的输出是:

list3 = [(a, p, q),
         (b, c, r, s),
         (d, e, t),
         (f, g, h, u, v, w) ]

可以在没有任何外部库的情况下完成此操作吗? 注意: len(列表1) = len(列表2)

beginner to python here.

I have 2 nested lists that I want to merge:

list1 = ['a',
         (b, c),
         (d, e),
         (f, g, h) ]

list2 = [(p,q),
         (r, s),
         (t),
         (u, v, w) ]

the output I am looking for is:

list3 = [(a, p, q),
         (b, c, r, s),
         (d, e, t),
         (f, g, h, u, v, w) ]

Can this be done without any external libraries?
note: len(list1) = len(list2)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

Spring初心 2024-12-17 16:18:45

使用 zip 函数和 列表推导式

list1 = [('a', ),
        ('b', 'c'),
        ('d', 'e'),
        ('f', 'g', 'h') ]

list2 = [('p', 'q'),
        ('r', 's'),
        ('t', ),
        ('u', 'v', 'w') ]

print [a + b for a, b in zip(list1, list2)]

Use the power of the zip function and list comprehensions:

list1 = [('a', ),
        ('b', 'c'),
        ('d', 'e'),
        ('f', 'g', 'h') ]

list2 = [('p', 'q'),
        ('r', 's'),
        ('t', ),
        ('u', 'v', 'w') ]

print [a + b for a, b in zip(list1, list2)]
吹泡泡o 2024-12-17 16:18:45
from operator import add
list3 = map(add, list1, list2)
from operator import add
list3 = map(add, list1, list2)
指尖上的星空 2024-12-17 16:18:45

如果内部列表/元组内的顺序并不重要,您可以使用数学集合运算。

print [tuple(set(a)|set(b)) for a,b in zip(x,y)]

set(a)|set(b) 将可迭代对象 a 和 b 转换为集合并取并集两套。然后根据输出格式将它们转换回元组。

由于您是 Python 初学者,强烈建议您掌握列表推导式。它太强大和简洁了。除了使代码更加“Pythonic”之外,列表推导式还可以作为“map”和“filter”函数的更友好的替代品。

If the order within an inner list/tuple is not important, you can use the mathematical set operations.

print [tuple(set(a)|set(b)) for a,b in zip(x,y)]

The set(a)|set(b) converts the iterables a and b to sets and takes the union of the two sets. They are then converted back to tuple as desired in the output format.

As you are a beginner to python, it is strongly recommended to master list comprehensions. It is way too powerful and concise. In addition to making your code more 'pythonic', list comprehensions can act as a friendlier replacement to 'map' and 'filter' functions.

删除会话 2024-12-17 16:18:45

简单一

list_3 = []
list_3.extend(list_1 + list_2)

Easy One

list_3 = []
list_3.extend(list_1 + list_2)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文