use*_*300 1 python indexing for-loop list
我希望能够交错两个可能长度不等的列表.我有的是:
def interleave(xs,ys):
a=xs
b=ys
c=a+b
c[::2]=a
c[1::2]=b
return c
Run Code Online (Sandbox Code Playgroud)
这适用于长度相等或只有+/- 1的列表.但是如果让我们说xs = [1,2,3]和ys = ["hi,"bye","no","yes","why"]这条消息出现:
c[::2]=a
ValueError: attempt to assign sequence of size 3 to extended slice of size 4
Run Code Online (Sandbox Code Playgroud)
如何使用索引修复此问题?或者我必须使用for循环?编辑:我想要的是让额外的值出现在最后.
你可以itertools.izip_longest在这里使用:
>>> from itertools import izip_longest
>>> xs = [1,2,3]
>>> ys = ["hi","bye","no","yes","why"]
>>> s = object()
>>> [y for x in izip_longest(xs, ys, fillvalue=s) for y in x if y is not s]
[1, 'hi', 2, 'bye', 3, 'no', 'yes', 'why']
Run Code Online (Sandbox Code Playgroud)
使用itertools中的roundrobin配方,此处不需要标记值:
from itertools import *
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)
演示:
>>> list(roundrobin(xs, ys))
[1, 'hi', 2, 'bye', 3, 'no', 'yes', 'why']
>>> list(roundrobin(ys, xs))
['hi', 1, 'bye', 2, 'no', 3, 'yes', 'why']
Run Code Online (Sandbox Code Playgroud)
你可以使用heapq.merge:
xs = [1, 2, 3]
ys = ['hi', 'bye', 'no', 'yes', 'why']
import heapq
interleaved = [v for i, v in heapq.merge(*[enumerate(el) for el in (xs, ys)])]
# [1, 'hi', 2, 'bye', 3, 'no', 'yes', 'why']
Run Code Online (Sandbox Code Playgroud)
这避免了对标记值和展平的需要.
使用roundrobin配方代替更有效地实现这一目标,而无需比较项目.