Alt*_*ift -3 python python-3.x
我从API获取数据并使用转换JSON requests
,然后从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']]
Run Code Online (Sandbox Code Playgroud)
输出根据需要给出了名称列表,但是后面跟着6个无值的列表; 我不明白为什么.
这些是列表推导中所有打印函数调用的返回值.
>>> x = print('hello')
hello
>>> print(x)
None
Run Code Online (Sandbox Code Playgroud)
而不是列表理解,只需使用常规循环:
for astronaut in astros['people']:
print(astronaut['name'])
Run Code Online (Sandbox Code Playgroud)
列表推导仅在您希望保留创建的实际列表时使用.