【发布时间】:2018-09-03 23:24:53
【问题描述】:
【问题讨论】:
-
请不要粘贴您的代码截图。粘贴代码本身。 Why not upload images of code on SO when asking a question?
-
我很抱歉;我不知道如何描绘空输出。由于回答部分有编码示例,截图我就不删了。
【问题讨论】:
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
【讨论】:
你可以使用这个:
list(map(sum,W))
或者这个:
{*map(sum,W)}
【讨论】: