python - Python3.x 中的映射迭代器对象是否只能使用一次,为什么? (附上代码和例子)

标签 python python-3.x list mutable

使用这段代码:

strs = ["111", "1000", "1000", "1000"]
# count the numbers of '0' and '1' respectively for each string in strs 
counts = map(lambda x: [x.count('0'), x.count('1')], strs)

cntSortBy0 = sorted(counts, key=lambda x: x[0])  # sort with counts of '0'

cntSortBy1 = sorted(counts, key=lambda x: x[1])  # sort with counts of '1'

这里我有一个以字符串作为元素的列表 strs

然后我分别计算 strs 中每个字符串的 '0' 和 '1' 的数量,并将结果保存在 counts 中(我在 python3 中使用 map 进行了此操作,所以 count 是一个 map 对象)。

之后我第一次对 counts 进行排序,它工作正常, 但是当我第二次对 counts 进行排序时,它返回一个空列表(cntSortBy1 为空),

我发现这是因为 counts第一次排序后 变空了:

>>> strs = ["111", "1000", "1000", "1000"]
>>>  counts = map(lambda x: [x.count('0'), x.count('1')], strs)
>>> cntSortBy0 = sorted(counts, key=lambda x: x[0])  # sort with counts of '0'
>>> list(counts)
[]

难怪 cntSortBy1 是空的,但为什么会发生这种情况?

此外,如果我只是打印list(counts)cntSortBy1也会变成空的,如下图,

>>> strs = ["111", "1000", "1000", "1000"]
>>> counts = map(lambda x: [x.count('0'), x.count('1')], strs)
>>> list(counts)
[[0, 3], [3, 1], [3, 1], [3, 1]]
>>> cntSortBy0 = sorted(counts, key=lambda x: x[0])
>>> cntSortBy0
[]
  • 这是否意味着一个 map 对象只能使用一次,之后它将变成一个空列表?

  • Py3 中是否有其他具有相同特性的对象? (我试过range(),不行。)

非常感谢!!!

最佳答案

在 Python3 中,map 返回一个迭代器: https://docs.python.org/3/library/functions.html#map

迭代器可以(也应该)只使用一次。请参阅有关迭代器的官方文档: https://docs.python.org/3/tutorial/classes.html#iterators

在您的情况下,您需要在创建时将 map 转换为 list,这将解决您的问题:

counts = list(map(lambda x: [x.count('0'), x.count('1')], strs))

关于python - Python3.x 中的映射迭代器对象是否只能使用一次,为什么? (附上代码和例子),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55951264/

相关文章:

c# - 遍历列表并删除项目的正确方法

python - 如何使用 Selenium WebDriver 打开网站并填写输入

python-3.x - H2O 目标均值编码器 "frames are being sent in the same order"错误

python - 根据其他两列的字符串创建 Pandas 数据框列

python - 同等权重的网格管理器中按钮大小不同?

c - 编译程序上没有使用 GDB 的符号表

Python - 将类似列表的字符串转换为列表列表的最快和最有效的方法

python - 为什么 numpy.ndarray.resize() 返回 None

Python按组创建线性回归预测pandas数据帧

python - 删除具有重复索引的 pandas 行