问题描述
我希望能够交叉两个可能长度不等的列表。我所拥有的是:pre $ def $ interleave(xs,ys):
a = xs
b = ys
c = a + b
c [:: 2] = a
c [1 :: 2] = b
返回c
这对于长度相等或者仅为+/- 1的列表非常有用。但是,如果我们说xs = [1,2,3]和ys = [hi,bye,no,yes,why],则会显示以下消息:
c [:: 2] = a
ValueError:尝试将大小为3的序列分配给大小为4的扩展片
如何使用索引来解决这个问题?还是我必须使用for循环?
编辑:我想要的是额外的值只出现在最后。
您可以使用这里:
>>> from itertools import izip_longest
>>> xs = [1,2,3]
> ;>> ys = [hi,bye,no,yes,why]
>>> s = object()
>>如果y不是s,则为y中的y在x中的y为x中的x,ys,fillvalue = s中的x。 ,'yes','why']
roundrobin
来自的配方,
$ b
from itertools import *
def roundrobin(* iterables):
roundrobin('ABC','D','EF') - > ADEBFC
#配方记入George Sakkis
pending = len(iterables)
nexts =循环(iter(it).next for iterables)
while pending:
尝试:
用于下一个下一个:
yield next()
除了StopIteration:
pending - = 1
nexts = cycle(islice(nexts,pending) )
演示:
>>>> list(roundrobin(xs,ys))
[1,'hi',2,'bye',3,'no' ,'yes','why']
>>> list(roundrobin(ys,xs))
['hi',1,'bye',2,'no',3 ,'是','为什么']
I want to be able to interleave two lists that could potentially be unequal in length. What I have is:
def interleave(xs,ys):
a=xs
b=ys
c=a+b
c[::2]=a
c[1::2]=b
return c
This works great with lists that either equal in length or just +/-1. But if let's say xs=[1,2,3] and ys= ["hi,"bye","no","yes","why"] this message appears:
c[::2]=a
ValueError: attempt to assign sequence of size 3 to extended slice of size 4
How do I fix this with using indexing? or do I have to use for loops? EDIT: what I want is to have the extra values just appear at the end.
You can use itertools.izip_longest
here:
>>> 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']
Using roundrobin
recipe from itertools, no sentinel value required here:
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))
Demo:
>>> list(roundrobin(xs, ys))
[1, 'hi', 2, 'bye', 3, 'no', 'yes', 'why']
>>> list(roundrobin(ys, xs))
['hi', 1, 'bye', 2, 'no', 3, 'yes', 'why']
这篇关于交错两列不等长的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!