Python 中的交错列表[重复]
- 2025-03-21 09:06:00
- admin 原创
- 38
问题描述:
我有两个清单:
[a, b, c] [d, e, f]
我想要:
[a, d, b, e, c, f]
在 Python 中执行此操作的简单方法是什么?
解决方案 1:
这是一个使用列表推导的非常简单的方法:
>>> lists = [['a', 'b', 'c'], ['d', 'e', 'f']]
>>> [x for t in zip(*lists) for x in t]
['a', 'd', 'b', 'e', 'c', 'f']
或者如果你将列表作为单独的变量(如其他答案中所述):
[x for t in zip(list_a, list_b) for x in t]
解决方案 2:
chain.from_iterable()
一种选择是使用和的组合zip()
:
# Python 3:
from itertools import chain
list(chain.from_iterable(zip(list_a, list_b)))
# Python 2:
from itertools import chain, izip
list(chain.from_iterable(izip(list_a, list_b)))
编辑:正如 sr2222 在评论中指出的那样,如果列表的长度不同,则此方法效果不佳。在这种情况下,根据所需的语义,您可能需要使用文档配方部分中的(更通用的
)roundrobin()
函数:itertools
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
解决方案 3:
这个只在 python 2.x 中有效,但适用于不同长度的列表:
[y for x in map(None,lis_a,lis_b) for y in x]
解决方案 4:
您可以使用内置函数做一些简单的事情:
sum(zip(list_a, list_b),())
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD