Python 如果多个列表项以字符串形式组合在一起
我有一本关于国家及其字母代码的字典Python 如果多个列表项以字符串形式组合在一起,python,list,Python,List,我有一本关于国家及其字母代码的字典 all_countries = { ... "Cambodia": "KH", "Saint Kitts and Nevis": "KN", "Comoros": "KM", "Sao Tome and Principe": "ST", "Slo
all_countries = {
...
"Cambodia": "KH",
"Saint Kitts and Nevis": "KN",
"Comoros": "KM",
"Sao Tome and Principe": "ST",
"Slovakia": "SK",
"Korea, Republic of": "KR",
"Slovenia": "SI",
"Korea, Democratic People's Republic of": "KP",
"Kuwait": "KW",
"Senegal": "SN",
....
}
我需要在下面的列表中将国家名称替换为字母2代码
....
["Pusan National University Hospital", "49241 Busan", "Korea", "Republic of"]
["Severance Hospital", "03722 Seoul", "Korea", "Republic of"]
["Ospedale degli Infermi", "47923 Rimini", "Italy"]
....
输出应为:
....
["Pusan National University Hospital", "49241 Busan", "KR"]
["Severance Hospital", "03722 Seoul", "KR"]
["Ospedale degli Infermi", "47923 Rimini", "IT"]
....
我有一个脚本来改变它
def get_alpha_code(row):
for i in row:
if i in all_countries.keys():
country_code = all_countries[i]
row.remove(i)
return country_code
elif i in all_countries.values():
code = i
row.remove(i)
return code
return None
但我如何检查字典键中是否有多个项目?
例如韩国这是工作吗?我没有你们所有的全部数据,但我想我们的想法是把字符串组合成你们的dict格式
all_countries = {
"Cambodia": "KH",
"Saint Kitts and Nevis": "KN",
"Comoros": "KM",
"Sao Tome and Principe": "ST",
"Slovakia": "SK",
"Korea, Republic of": "KR",
"Slovenia": "SI",
"Korea, Democratic People's Republic of": "KP",
"Kuwait": "KW",
"Senegal": "SN",
"Italy": "IT",
}
a = [["Pusan National University Hospital", "49241 Busan", "Korea", "Republic of"],
["Severance Hospital", "03722 Seoul", "Korea", "Republic of"],
["Ospedale degli Infermi", "47923 Rimini", "Italy"]]
def process_data(a):
ll = []
for row in a:
if len(row) == 3:
c = row[-1]
elif len(row) == 4:
c = row[-2]+', '+row[-1]
rr = row[0:2]+[all_countries[c]]
ll.append(rr)
return ll
process_data(a)
在您的列表“Korea”中,“Republic of”是两个不同的元素,但在字典中是单键Yes。所以我需要检查一下?这两个不同的元素可能是国家的全称如何识别这两个元素?您不需要更改dict,只需将数据转换为dict之后的格式。