python - 创建子列表时填充
问题描述
有没有一种优雅的方法如何在从整数列表创建子列表时用零填充最后一个子列表?
到目前为止,我有这个 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]
解决方案
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]]
推荐阅读
- php - laravel中带有env变量的主动静态属性
- python - os.path.expanduser("~") 不在heroku上工作
- css - 放置一个带有背景图像的响应式 SVG
- ada - C++ 中#define 的 Ada 等价物是什么?
- postgresql - 在postgresql中使用连接的列作为函数表的参数
- ruby-on-rails - 使用 remote_xxx_url 时,Carrierwave 正在为具有透明背景的图像添加黑色背景
- node.js - 我将如何制作 discord.js 订阅系统
- vhdl - 如何测试基准 VHDL 信号并在 GTKWAVE 中显示它们?
- json - 将数组外的元素添加到 csv 输出
- ruby-on-rails - 为什么&运算符的输出与任何逻辑运算都不会在Ruby中给出任何输出?