答案 0 :(得分:4)
map返回一个迭代器,您只能使用一次迭代器。
示例:
>>> a=map(int,[1,2,3])
>>> a
<map object at 0x1022ceeb8>
>>> list(a)
[1, 2, 3]
>>> next(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> list(a)
[]
另一个示例,我使用第一个元素并创建带有其余元素的列表
>>> a=map(int,[1,2,3])
>>> next(a)
1
>>> list(a)
[2, 3]
答案 1 :(得分:0)
根据@newbie的回答,发生这种情况是因为您在使用map迭代器之前就使用了它。 ({@ {3}}是来自@LukaszRogalski的另一个很好的答案)
示例1:
w = [[1,5,7],[2,2,2,9],[1,2],[0]]
m = map(sum,w) # map iterator is generated
list(m) # map iterator is consumed here (output: [13,15,3,0])
for v in m:
print(v) # there is nothing left in m, so there's nothing to print
示例2:
w = [[1,5,7],[2,2,2,9],[1,2],[0]]
m = map(sum,w) #map iterator is generated
for v in m:
print(v) #map iterator is consumed here
# if you try and print again, you won't get a result
for v in m:
print(v) # there is nothing left in m, so there's nothing to print
因此,您在此处有两个选择,如果您只想对列表进行一次迭代,则示例2 可以正常工作。但是,如果您希望能够继续使用m
作为代码列表,则需要修改示例1 ,如下所示:
示例1(已修改):
w = [[1,5,7],[2,2,2,9],[1,2],[0]]
m = map(sum,w) # map iterator is generated
m = list(m) # map iterator is consumed here, but it is converted to a reusable list.
for v in m:
print(v) # now you are iterating a list, so you should have no issue iterating
# and reiterating to your heart's content!
答案 2 :(得分:0)
这是因为它返回了一个更清晰的示例生成器:
>>> gen=(i for i in (1,2,3))
>>> list(gen)
[1, 2, 3]
>>> for i in gen:
print(i)
>>>
所以最好的办法是:
>>> M=list(map(sum,W))
>>> M
[13, 15, 3, 0]
>>> for i in M:
print(i)
13
15
3
0
答案 3 :(得分:0)
您可以使用此:
list(map(sum,W))
或者这个:
{*map(sum,W)}