Python:合并嵌套列表
初学者在这里。
我有 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
zip
函数和 列表推导式:Use the power of the
zip
function and list comprehensions:如果内部列表/元组内的顺序并不重要,您可以使用数学集合运算。
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.
简单一
Easy One