【问题标题】:Where is this list of None coming from? [duplicate]这个 None 列表来自哪里? [复制]
【发布时间】:2018-08-16 00:29:37
【问题描述】:

我正在从 API 获取数据并使用 requests 转换 JSON,然后从 dict 列表中的每个 dict 中提取一个值:

response = requests.get("http://api.open-notify.org/astros.json")
astros = response.json()
print(astros["number"])
[print(astronaut['name']) for astronaut in astros['people']]

输出根据需要提供名称列表,但在此之后是 6 个 None 值的列表;我不明白为什么。

【问题讨论】:

  • 注。我在 Jupyter Notebook 中运行代码。

标签: python python-3.x


【解决方案1】:

这些是列表推导中所有打印函数调用的返回值。

>>> x = print('hello')
hello
>>> print(x)
None

而不是列表推导式,只需使用常规循环:

for astronaut in astros['people']:
    print(astronaut['name'])

列表推导式仅在您希望创建实际列表时使用。

【讨论】:

  • "列表推导仅在您希望保留实际创建的列表时使用。"附录:“并且永远不应该用于副作用”(例如printing)。列表推导是对代码阅读器的提示,它是将可迭代的输入简单地转换为输出列表,没有任何距离;违反这一点,你正在编写不必要的混乱代码。
  • 所以,在尝试变得更像 Pythonesque 时,我实际上并没有那么像。谢谢大家!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-04
  • 2021-11-14
  • 1970-01-01
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多