Dict / List max by key

时间:2017-01-18 15:38:39

标签: python list dictionary

我有以下词典:

[{'country': 'Armenia', 'population': '3026048'}, {'country': 'Angola', 'population': '25830958'}, {'country': 'Algeria', 'population': '40375954'}, {'country': 'Andorra', 'population': '69165'}, {'country': 'Anguilla', 'population': '14763'}, {'country': 'American Samoa', 'population': '55602'}, {'country': 'Aruba', 'population': '104263'}, {'country': 'Argentina', 'population': '43847277'}, {'country': 'Afghanistan', 'population': '33369945'}, {'country': 'Azerbaijan', 'population': '9868447'}, {'country': 'Australia', 'population': '24309330'}, {'country': 'Antigua and Barbuda', 'population': '92738'}, {'country': 'Albania', 'population': '2903700'}, {'country': 'Austria', 'population': '8569633'}]

以及以下列表

[['Andorra', '69165'], ['Afghanistan', '33369945'], ['Algeria', '40375954'], ['American Samoa', '55602'], ['Aruba', '104263'], ['Armenia', '3026048'], ['Angola', '25830958'], ['Azerbaijan', '9868447'], ['Antigua and Barbuda', '92738'], ['Australia', '24309330'], ['Albania', '2903700'], ['Argentina', '43847277'], ['Anguilla', '14763'], ['Austria', '8569633']]

如何提取人口最多的国家/地区的国家/地区名称(每个子列表中的第二个值)

您可以为列表或词典提供解决方案。

2 个答案:

答案 0 :(得分:7)

您可以将max与密钥一起使用,对于列表,它将是:

max(lst, key = lambda x: int(x[1]))
# ['Argentina', '43847277']

dict的想法相同,关键功能略有不同:

max(d, key = lambda x: int(x['population']))
# {'country': 'Argentina', 'population': '43847277'}

答案 1 :(得分:-1)

像这样的东西(列表清单):

pops = []

for small_list in big_list:
    pops.append(int(small_list[1]))

max_value = max(pops)
max_index = pops.index(max_value)

most_pop_country = big_list[max_index][0]
print(most_pop_country)

它基本上找到最大总体的索引,然后为其提取国家名称。