我发现有很多关于如何压缩不平等列表的问题/答案。但是,在所有情况下,结果集使用None填充较短列表的背面。我想在前面加上较短的清单。
list1 = [a, b, c, d, e] (pretend these are numbers)
list2 = [3, 4, 5]
fun(list1, list2) => [(a, None), (b, None), (c, 3), (d, 4), (e, 5)]
加成:
fun(list1, list2) => [(a, 0), (b, 0), (c, 3), (d, 4), (e, 5)]
答案 0 :(得分:3)
from itertools import zip_longest
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = [3, 4, 5]
result = [tup for tup in zip_longest(list1[::-1], list2[::-1], fillvalue=0)][::-1]
print(result)
# [('a', 0), ('b', 0), ('c', 3), ('d', 4), ('e', 5)]
答案 1 :(得分:1)
def left_pad_list(a_list,n,fillval=None):
return [fillval]*(n-len(a_list)) + list(a_list)
我猜? (然后确定哪个更长/更短)
my_lists = [list1,list2,list3]
max_len = max(my_lists,key=len)
my_new_lists = [left_pad_list(x,max_len,0) for x in my_lists]