簡體   English   中英

如何僅在 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打印汽車模型,你可以使用列表理解

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

如上所示,要訪問字典值,您需要指定鍵,例如x['cars'] ,其中'cars'是字典中的 您可以查看文檔以獲取有關如何使用字典的更多有用信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM