python - 如何找到 itertools.izip_longest 的长度

标签 python

我在“itertools.izip_longest”中存储了很多元组

我正在尝试遍历 itertools.izip_longest 中包含的这些元组以更改某些值,如下面的代码所示

for i in range(len(pixels)):
  if i >= 2148 and i <= 3505:
    if pixels[i][0] == 146: # assuming each data element is a 3 element tuple
     pixels[i][0] += 1

然而,当我尝试运行代码时,出现与长度相关的错误:

  for i in range(len(pixels)):
TypeError: object of type 'itertools.izip_longest' has no len()

我如何找到 itertools.izip_longest 中包含的长度(元组数)

谢谢

最佳答案

izip_longest 返回 generator ,其中返回的每个项目都是动态生成的。如果你想知道可迭代对象中有多少项,你可以这样做

len(list(pixels))

这和

是一样的
len([item for item in pixels])

例子:

In [1]: from itertools import izip_longest

In [2]: x = izip_longest(range(10), range(100))

In [3]: len(x)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-e62f33f06233> in <module>()
----> 1 len(x)

TypeError: object of type 'itertools.izip_longest' has no len()

In [4]: len(list(x))
Out[4]: 100

关于python - 如何找到 itertools.izip_longest 的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26165710/

相关文章:

python - 如何对 csv 中的 'date' 列进行排序以仅显示年度范围的 Spring 数据

python - 增加每秒请求量

python - Anaconda 4.3.1 Navigator 无法在 macOS Sierra 10.12.4 上打开

python - pymc3多元traceplot颜色编码

python - 追加到列表中的几个列表

python date.min 不会转换回来。为什么?

python - 双 for 循环到 Python 列表理解

python - 查看以前的时间序列

python - 在python3.8中的自记录f字符串中的等号后插入换行符

python - 如何删除嵌套容器中的重复条目