【问题标题】:Python - Printing Map Object IssuePython - 打印地图对象问题
【发布时间】:2018-09-03 23:24:53
【问题描述】:

我正在玩地图对象,并注意到如果我事先执行 list() 它不会打印。当我事先只查看地图时,打印工作正常。为什么?

【问题讨论】:

标签: python jupyter-notebook


【解决方案1】:

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]

【讨论】:

  • 谢谢新手;这是有道理的。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    这是因为它返回了一个生成器所以更清晰的例子:

    >>> 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
    

    【讨论】:

      【解决方案4】:

      你可以使用这个:

      list(map(sum,W))
      

      或者这个:

      {*map(sum,W)}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多