def over(xs,ys):
如何使用xs的第一个值创建一个新列表,然后是ys的第一个值,然后是xs的第二个值,ys的第二个值,依此类推。
例如
([1,2,3], ["hi", "bye",True, False, 33]) ===> [1, "hi", 2, "bye", 3, True, False, 33]
答案 0 :(得分:4)
在Python 2.X上:
>>> data = ([1,2,3], ["hi", "bye",True, False, 33])
>>> [x for t in map(None, *data) for x in t if x is not None]
[1, 'hi', 2, 'bye', 3, True, False, 33]
在Python 3.x上:
>>> from itertools import zip_longest
>>> data = ([1,2,3], ["hi", "bye",True, False, 33])
>>> [x for t in zip_longest(*data) for x in t if x is not None]
[1, 'hi', 2, 'bye', 3, True, False, 33]
你应该毫不犹豫地使用itertools / zip_longest。但是,如果你想要有好奇心:
def oldMapNone(*ells):
'''replace for map(None, ....), invalid in 3.0 :-( '''
lgst=len(max(ells, key=len))
return list(zip(*[list(e) + [None] * (lgst - len(e)) for e in ells]))
data = ([1,2,3], ["hi", "bye",True, False, 33])
print([x for t in oldMapNone(*data) for x in t if x is not None])
# [1, 'hi', 2, 'bye', 3, True, False, 33]
适用于任何Python版本。我建议不要优先考虑itertools版本。
答案 1 :(得分:0)
>>> l1
[1, 2, 3]
>>> l2
['hi', 'bye', True, False, 33]
>>>
>>>
>>> while l1 or l2:
... if l1: l1.pop(0)
... if l2: l2.pop(0)
...
1
'hi'
2
'bye'
3
True
False
33