You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python zip()函数合并列表并消除多余嵌套括号

实现zip合并列表后的扁平化输出

你的问题出在最后一行的列表推导式——[list(a) for a in zip(lst1,lst2)]会把zip()返回的每个元组转换成独立的子列表,最终得到嵌套结构。要得到扁平化的列表,你可以用以下几种方法:

方法1:双层列表推导式(直观易读)

直接遍历zip()生成的每个配对元组,再逐个提取元组里的元素:

lst1 = [int(item) for item in input("Enter the list items : ").split()]
lst2 = [int(item) for item in input("Enter the list items : ").split()]

print(lst1)
print(lst2)

# 扁平化输出
print([num for pair in zip(lst1, lst2) for num in pair])

运行后就能得到你想要的[1, 1, 2, 2, 3, 3, 4, 4, 5, 5]。

方法2:使用itertools.chain(高效处理大列表)

如果你的列表数据量很大,推荐用itertools.chain.from_iterable来惰性迭代扁平化,避免创建中间嵌套列表,提升效率:

from itertools import chain

lst1 = [int(item) for item in input("Enter the list items : ").split()]
lst2 = [int(item) for item in input("Enter the list items : ").split()]

print(lst1)
print(lst2)

# 扁平化输出
print(list(chain.from_iterable(zip(lst1, lst2))))

方法3:用sum拼接(不推荐大列表)

可以利用sum()函数把元组逐个累加,但这种方法在处理大列表时效率很低,因为每次拼接都会生成新的序列:

lst1 = [int(item) for item in input("Enter the list items : ").split()]
lst2 = [int(item) for item in input("Enter the list items : ").split()]

print(lst1)
print(lst2)

# 扁平化输出,需转成列表
print(list(sum(zip(lst1, lst2), ())))

内容的提问来源于stack exchange,提问作者Usman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 06:35:30