You can download this code by clicking the button below.
This code is now available for download.
Combines multiple lists into a new list, filling the shorter lists with fillvalue if they are of different lengths.
Technology Stack : itertools.zip_longest
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*args, fillvalue=0):
"""将可变长度的列表组合成一个新的列表,如果某个列表较短,则使用fillvalue填充。
Args:
*args: 可变数量的列表。
fillvalue: 填充较短列表的值。
Returns:
一个新的列表,包含所有输入列表中的元素,较短的列表使用fillvalue填充。
"""
# 使用内置库itertools中的zip_longest函数
from itertools import zip_longest
# 使用列表推导式来生成结果列表
return [item for tup in zip_longest(*args, fillvalue=fillvalue) for item in tup]