python - 如何在 Python 3 中对列表进行分块?

标签 python list python-3.x

我找到了以下与python2兼容的代码

from itertools import izip_longest
def grouper(n, iterable, padvalue=None):
  "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
  return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue)

但是,这不适用于 Python 3。我收到以下错误

ImportError: cannot import name izip_longest

有人可以帮忙吗?

我想将我的 [1,2,3,4,5,6,7,8,9] 列表转换为 [[1,2,3] ,[4,5,6],[7,8,9]]

编辑

现在兼容 Python3

以下代码改编自所选答案。只需将名称从 izip_longest 更改为 zip_longest

from itertools import zip_longest
def grouper(n, iterable, padvalue=None):
  "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
  return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)

最佳答案

在 Python 3 的 itertools 中有一个名为 zip_longest 的函数。它应该和 Python 2 中的 izip_longest 一样。

为什么要改名?您可能还注意到 itertools.izip 现在在 Python 3 中消失了 - 这是因为在 Python 3 中,zip 内置函数现在返回一个迭代器,而在 Python 2 中它返回一个列表。由于不需要 izip 函数,因此重命名 _longest 变体以保持一致性也是有意义的。

关于python - 如何在 Python 3 中对列表进行分块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5850536/

相关文章:

python-3.x - 如何根据数据框 pandas 的唯一首字母构建新列

python - 如何使用 Python 在 MySQL 数据库中存储 API 响应?

Python 2.6 TreeMap/SortedDictionary?

python - 如何找到列表中最长的列表?

c# - 尝试对没有所有元素的数组列表进行排序

python - 如何访问与保留关键字同名的属性?

基于 Python tile 的 numpy 数组处理

python - 从单词列表中查找字符出现百分比

python - 从 {index : list of row values} 形式的字典构造 Pandas DataFrame

python - 如何使用 PILLOW 临时转换图像?