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]
根据@newbie的回答,这种情况正在发生,因为在使用之前你正在使用map迭代器。 (Here是@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!
这是因为它返回一个发电机更清晰的例子:
>>> 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