在python中将3个列表组合成一个字典列表

2024-09-23 22:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始学Python,对它完全不在行。所以我要做的是把3个列表合并成一个字典列表

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

以下格式的列表:

^{pr2}$

然后按以下格式打印新列表:

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.

Tags: andofthe列表iscurrencytokyocapital
1条回答
网友
1楼 · 发布于 2024-09-23 22:29:51

使用zip进行简单的列表理解就足够了:

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

然后可以迭代data并按如下方式打印:

^{pr2}$

可读性提示

请注意,与括号内的所有结构一样,您可以将列表理解拆分为多行:

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))

相关问题 更多 >