使用这段代码:
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/