簡體   English   中英

將3個列表合並為python中的詞典列表

[英]Combining 3 Lists into a lists of dictionaries in python

我才剛剛開始學習Python,並且對它完全陌生。 所以我要做的是將3個列表合並成一個字典列表

country= ["Japan", "Malaysia", "Philippine", "Thailand"]
capital = ["Tokyo", "Kuala Lumpur", "Manila", "Bangkok"]
currency = ["Yen", "Ringgit", "Peso", "Bath"]

變成以下格式的列表:

data = [{"country":"Japan", "capital":"Tokyo", "currency":"Yen"}, {"country":"Malaysia", "capital":"Kuala Lumpur", "currency":"Ringgit"}, {"country":"Philippine", "capital":"Manila", "currency":"Peso"},{"country":"Thailand", "capital":"Bangkok", "currency":"Bath"}]

然后以這種格式打印新列表:

Capital of Japan is Tokyo, and the currency is Yen.
Capital of Malaysia is Kuala Lumpur, and the currency is Ringgit.
Capital of Philippine is Manila, and the currency is Peso.
Capital of Thailand is Bangkok, and the currency is Bath.

您只需使用zip簡單的列表理解即可:

data = [{'country':coun, 'capital': cap, 'currency': curr} for coun, cap, curr in zip(country, capital, currency)]

然后,您可以遍歷data並按以下方式進行打印:

for dictionary in data:
    print("Capital of {0} is {1} and currency is {2}".format(dictionary['country'],dictionary['capital'], dictionary['currency']))

可讀性提示

請注意,就像方括號內的所有結構一樣,您可以將列表理解分為多行:

data = [{'country':coun, 'capital': cap, 'currency': curr}
        for coun, cap, curr in zip(country, capital, currency)
       ]

您可能還希望將字符串保存為變量格式(可能帶有其他常量),以免最終被其他語句掩埋:

message = "Capital of {0} is {1} and currency is {2}"
for dictionary in data:
    print(message.format(dictionary['country'],dictionary['capital'], dictionary['currency']))

您還可以在格式空間而不是{0} {1}指定鍵,然后使用.format_map將鍵從字典映射到字符串:

message = "Capital of {country} is {capital} and currency is {currency}"
for dictionary in data:
    print(message.format_map(dictionary))

暫無
暫無

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

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