【问题标题】:Why is the output of this script a list of None? [duplicate]为什么这个脚本的输出是一个无列表? [复制]
【发布时间】:2021-04-13 08:36:24
【问题描述】:

我知道这是一个简单的问题,但我想知道它为什么打印None。直接从我的终端编码时,它只会打印 None 。如果我在文件或在线 Python 编译器中编写相同的代码然后运行它,我不会得到相同的输出。

直接从我的终端编码:

>>> b = [(1, 2), (3, 4), (5, 6)]
>>> [print(a) for a in b]
(1, 2)
(3, 4)
(5, 6)
[None, None, None]

在 Python 在线编译器中运行:

运行 Python 文件:

我知道不是同一个数组,但逻辑是一样的。

b = ([100.64188563286582, 101.64188563286582], [-1.0626228, -0.8626228], [-5.0, -15.0], [-float('inf'), float('inf')], [float('inf'), float('inf')], [-float('inf'), float('inf')], [-float('inf'), float('inf')])

[print(a) for a in b]

【问题讨论】:

  • 请将您的图片替换为粘贴的代码(作为文本)。
  • 您可能希望从列表理解中删除打印语句。你得到的首先是打印输出,然后是打印调用的返回值列表。
  • 你的问题有一个答案:stackoverflow.com/questions/28812851/…
  • 我用代码编辑了帖子
  • 基本上是因为函数print 返回无。在交互式解释器(您的终端)中执行的大多数语句都会打印返回的结果。

标签: python python-3.x


【解决方案1】:

[print(a) for a in b] 产生print() 对象的列表。正如您可以通过print(print()) 简单验证的那样,打印print() 对象列表将显示None 列表

【讨论】:

  • 没有“print 对象”这样的东西——print 不是一个类。
【解决方案2】:

不使用 print() ,因为 print(print()) 内部打印不返回任何东西,所以最后它给出了 None

>>>b=[(1,2),(3,4),(5,6)]
>>>[a for a in b]
>>>[(1, 2), (3, 4), (5, 6)]

输出:

[(1, 2), (3, 4), (5, 6)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 2015-09-24
    • 2023-03-03
    • 2018-10-10
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多