Python - 打印地图对象问题

问题描述 投票:0回答:3

我正在玩地图对象,并注意到如果我事先做list()就不打印。当我事先仅查看地图时,打印工作。为什么?

enter image description here

enter image description here

python jupyter-notebook
3个回答
5
投票

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]

0
投票

根据@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!

0
投票

这是因为它返回一个发电机更清晰的例子:

>>> gen=(i for i in (1,2,3))
>>> list(gen)
[1, 2, 3]
>>> for i in gen:
    print(i)


>>> 

Explanation:

  • 这是因为将它转换为列表它基本上循环低于你想再次循环后它会认为仍然继续但没有更多的元素

所以最好的办法是:

>>> M=list(map(sum,W))
>>> M
[13, 15, 3, 0]
>>> for i in M:
        print(i)
13
15
3
0
© www.soinside.com 2019 - 2024. All rights reserved.