最简单的方法:
result = list(roundrobin(list_01, list_02, list_03))
只需从Itertools Recipes复制&粘贴roundrobin
,或者根据配方部分所提到的,在more-itertools中导入它。
另外,我喜欢使用heapq.merge
:
result = list(map(itemgetter(1), merge(*map(enumerate, lists), key=itemgetter(0))))
变种:
index, value = map(itemgetter, (0, 1))
result = list(map(value, merge(*map(enumerate, lists), key=index)))
完整代码(在线尝试):
from operator import itemgetter
from heapq import merge
list_01 = ['DOG','CAT','BEAR']
list_02 = ['V','W','X','Y','Z']
list_03 = ['A','B','C','D','E','F','G','H']
lists = list_01, list_02, list_03
expect = ['DOG','V','A','CAT','W','B','BEAR','X','C','Y','D','Z','E','F','G','H']
result = list(map(itemgetter(1), merge(*map(enumerate, lists), key=itemgetter(0))))
print(result == expect)
index, value = map(itemgetter, (0, 1))
result = list(map(value, merge(*map(enumerate, lists), key=index)))
print(result == expect)
zip_longest
中,您可以使用fillvalue=XXX
并填充一个您知道不会匹配的值,然后测试其相等性。 - mozwayobject()
就可以实现。 - no comment