如何压缩两个不同大小的列表?

时间:2019-03-07 06:56:38

标签: python list

我正在尝试压缩2个列表:

await

我想要的结果是这样

a = ["a","b","c","d","e"]
b = [1,2,3]

或如下所示,这是我要打印数据的方式:

[["a",1],["b",2],["c",3],["d"],["e"]]

我找到并尝试过的所有不同方法,要么停止在a 1 b 2 c 3 d e 的大小,要么再次从b重新开始。即:b,那不是我所需要的。

1 个答案:

答案 0 :(得分:0)

import itertools

a = ["a", "b", "c", "d", "e"]

b = [1, 2, 3]
# ans = [list(filter(None, i)) for i in list(itertools.zip_longest(a, b))] 
# list was redundant

a = [list(filter(None, i)) for i in itertools.zip_longest(a, b)]

print(ans)

输出:

[['a', 1], ['b', 2], ['c', 3], ['d'], ['e']]