And*_*ark 33
这是一个使用列表理解的非常直接的方法:
>>> lists = [['a', 'b', 'c'], ['d', 'e', 'f']]
>>> [x for t in zip(*lists) for x in t]
['a', 'd', 'b', 'e', 'c', 'f']
Run Code Online (Sandbox Code Playgroud)
或者,如果您将列表作为单独的变量(如在其他答案中):
[x for t in zip(list_a, list_b) for x in t]
Run Code Online (Sandbox Code Playgroud)
Sve*_*ach 29
一种选择是使用的组合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)))
Run Code Online (Sandbox Code Playgroud)
编辑:正如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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16457 次 |
| 最近记录: |