如何仅在 Python 中获取嵌套列表项值

How to get nested list items values only in Python

我有一个列表,我可以打印该列表。但是,我在列表中还有另一个列表。我只能获取嵌套列表中的特定项目吗?

例如:

import json

x = {
  "name": "John",
  "age": 30,
  "married": True,
  "divorced": False,
  "children": ("Ann","Billy"),
  "pets": None,
  "cars": [
    {"model": "BMW 230", "mpg": 27.5},
    {"model": "Ford Edge", "mpg": 24.1}
  ]
}

# convert into JSON:
y = json.dumps(x)

# the result is a JSON string:
print(y)

这里,如果我只想打印汽车模型,怎么打印?

喜欢,型号=BMW230

你能帮忙吗?谢谢。

你的数据结构x是一个字典。如果你只想打印字典 x 中的汽车模型,你可以使用 list comprehension:

print([car['model'] for car in x["cars"]])
# ['BMW 230', 'Ford Edge']

或者您可以使用正常的 for 循环打印每个模型:

for car in x['cars']:
    print(car['model'])

# BMW 230
# Ford Edge

如上所示,要访问字典 values,您需要指定键,例如 x['cars'],其中 'cars'字典中的键。您可以查看 documentation 以获得有关如何使用词典的更多有用信息。