0

我有两个长度可能不相等的列表,我希望能够将它们交错。我希望能够在交错列表末尾的较长列表中附加额外的值。我有这个:

def interleave(xs,ys):
a=xs
b=ys
minlength=[len(a),len(b)]
extralist= list()
interleave= list()
for i in range((minval(minlength))):
    pair=a[i],b[i]
    interleave.append(pair)
    flat=flatten(interleave)
    c=a+b
if len(b)>len(a):
    remainder=len(b)-len(a)
    print(remainder)
    for j in range(remainder,-1,-1):
        extra=b[-j]
        extralist.append(extra)
        print(extralist)
if len(a)>len(b):
    remainder=len(a)-len(b)
    print(remainder)
    for j in range(remainder,-1,-1):
        extra=a[-j]
        extralist.append(extra)
final=flat+extralist
return final

但如果我测试它:

>>> interleave([1,2,3], ["hi", "bye",True, False, 33])
[1, 'hi', 2, 'bye', 3, True]
>>> 

False 和 33 不会出现。我做错了什么?

编辑:我找到了解决方案。我向后索引:)

4

2 回答 2

3

这是使用itertools.zip_longest列表理解的解决方案:

>>> from itertools import zip_longest
>>> a = [1, 2, 3]
>>> b = ["hi", "bye", True, False, 33]
>>> [y for x in zip_longest(a, b) for y in x]
[1, 'hi', 2, 'bye', 3, True, None, False, None, 33]
>>> [y for x in zip_longest(a, b) for y in x if y is not None]
[1, 'hi', 2, 'bye', 3, True, False, 33]
>>>

编辑:

如果您不想使用itertools,我想您可以这样做:

>>> a = [1, 2, 3]
>>> b = ["hi", "bye", True, False, 33]
>>> items = sorted((a,b), key=len)
>>> out = []
>>> for x,y in enumerate(items[1]):
...     out.append(y)
...     try:
...         out.append(items[0][x])
...     except IndexError:
...         out.extend(items[1][x+1:])
...         break
...
>>> out
['hi', 1, 'bye', 2, True, 3, False, 33]
>>>

但我必须说这种方法不如我的第一个解决方案有效。


编辑2:

改成enumeratezip降低效率。但是,如果你必须这样做,那么你可以这样做:

>>> a = [1, 2, 3]
>>> b = ["hi", "bye", True, False, 33]
>>> out = []
>>> items = sorted((a,b), key=len)
>>> for x,y in zip(range(len(items[1])), items[1]):
...     out.append(y)
...     try:
...         out.append(items[0][x])
...     except IndexError:
...         out.extend(items[1][x+1:])
...         break
...
>>> out
['hi', 1, 'bye', 2, True, 3, False, 33]
>>>
于 2013-11-10T15:56:37.547 回答
0

另外的选择

from itertools import chain
x = [1, 2, 3]
y = iter(["hi", "bye",True, False, 33])
list(chain.from_iterable(zip(x, y))) + list(y)
[1, 'hi', 2, 'bye', 3, True, False, 33]
于 2013-11-10T16:23:37.567 回答