替代python 3中的zip?

时间:2019-06-17 09:47:00

标签: python merge concat

Python 3中的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']]

2 个答案:

答案 0 :(得分:0)

如果要避免同时压缩两个列表,我要做的方法是在try / except子句中附加两个列表中的值,并附加{{1}中的值}(或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

答案 1 :(得分:0)

您还可以在另一个列表中收集两个(或多个)列表,并使用嵌套列表理解来模拟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']]