如何交错列表

时间:2013-11-10 15:50:39

标签: python for-loop python-3.x user-defined-functions

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

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没有出现。我做错了什么?

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

2 个答案:

答案 0 :(得分:3)

以下是使用itertools.zip_longestlist comprehension

的解决方案
>>> 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:

enumerate更改为zip会再次降低效率。但是,如果你必须,那么你可以这样做:

>>> 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]
>>>

答案 1 :(得分: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]