首页 > 解决方案 > 创建子列表时填充

问题描述

有没有一种优雅的方法如何在从整数列表创建子列表时用零填充最后一个子列表?

到目前为止,我有这个 oneliner,需要用 2 个零填充最后一个子列表

[lst[x:x+3] for x in range(0, len(lst), 3)]

例如

lst =[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

结果应该是:

[1,2,3][4,5,6][7,8,9][10,0,0]

标签: pythonlist

解决方案


With itertools.zip_longest, consuming the same iterator created off of the list, and fill in the missing values as 0 :

[[*i] for i in itertools.zip_longest(*[iter(lst)] * 3, fillvalue=0)]

Example:

In [1219]: lst =[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]                                                                                                                                                            

In [1220]: [[*i] for i in itertools.zip_longest(*[iter(lst)] * 3, fillvalue=0)]                                                                                                                             
Out[1220]: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 0, 0]]

推荐阅读