python 3 中 zip 的替代方案?

Alternative for zip in python 3?

python3 中的 zip 替代方案?

from itertools import zip_longest 
list_1 = [["ele1"],["ele_2"],["ele_3"]]
list_2 = [["ele4"],["ele_5"]]

result = [[x for x in t if x is not None] for t in zip_longest(list_1,list_2)]
print(result)

我得到的输出是

[[['ele1'], ['ele4']], [['ele_2'], ['ele_5']], [['ele_3']]]

预期输出:

[['ele1'], ['ele4']], [['ele_2'], ['ele_5']], [['ele_3']]

如果你想避免使用压缩两个列表,我会这样做的方法是在 try/except 子句中附加来自两个列表的值,并附加来自 list_2 (或 list_1 如果它是两者中最短的)定义为迭代器,避免以这种方式在迭代时必须 zip 两个列表:

# iterate over the longest list. Define other as iterator
l2 = iter(list_2)
out = [[] for _ in range(len(list_1))]
for ix, i in enumerate(list_1): 
    try:
        out[ix].append(i)
        out[ix].append(next(l2))
    except StopIteration:
        break

给出:

print(out)
[[['ele1'], ['ele4']], [['ele_2'], ['ele_5']], [['ele_3']]]

您还可以将您的两个(或更多)列表收集到另一个列表中,并使用嵌套列表理解来模拟 zip_longest.

的行为
>>> lists = [list_1, list_2] # an also be more than two lists
>>> [[lst[i] for lst in lists if i < len(lst)]
...  for i in range(max(map(len, lists)))]
...
[[['ele1'], ['ele4']], [['ele_2'], ['ele_5']], [['ele_3']]]

(如果你在上面的表达式中将 max 换成 min,你会得到 zip。)

如果要打印没有最外层的结果[...]:

>>> print(', '.join(map(str, _)))                                          
[['ele1'], ['ele4']], [['ele_2'], ['ele_5']], [['ele_3']]