排序函数不返回列表列表的正确结果

时间:2018-03-30 17:26:48

标签: python

我有一份列表,我试图按人口密度排序。但是,排序的函数似乎没有正确地对它们进行排序。

cnt_pop_within_range = [['China', '139.54'], ['United States of America', '32.19'], ['Brazil', '22.72'], ['Canada', '3.43'], ['Indonesia', '144.00'], ['Mexico', '65.32'], ['Egypt', '93.38'], ['France', '119.39'], ['Italy', '199.34'], ['South Africa', '44.98'], ['Colombia', '44.60']]
print(sorted(cnt_pop_within_range, key = itemgetter(1), reverse = True))

这是打印到控制台上的内容:

> [['Egypt', '93.38'], ['Mexico', '65.32'], ['South Africa', '44.98'],
> ['Colombia', '44.60'], ['United States of America', '32.19'],
> ['Canada', '3.43'], ['Brazil', '22.72'], ['Italy', '199.34'],
> ['Indonesia', '144.00'], ['China', '139.54'], ['France', '119.39']]

2 个答案:

答案 0 :(得分:7)

更改排序功能以将元素转换为float,否则项目按字典顺序排列(作为字符串)而不是数字

>>> print(sorted(cnt_pop_within_range, key = lambda i: float(i[1]), reverse = True))
[['Italy', '199.34'], ['Indonesia', '144.00'], ['China', '139.54'], ['France', '119.39'], ['Egypt', '93.38'], ['Mexico', '65.32'], ['South Africa', '44.98'], ['Colombia', '44.60'], ['United States of America', '32.19'], ['Brazil', '22.72'], ['Canada', '3.43']]

答案 1 :(得分:-1)

您可以尝试排序方法:

cnt_pop_within_range.sort(key=lambda x:float(x[1]),reverse = True)

输出:

[['Egypt', '93.38'], ['Mexico', '65.32'], ['South Africa', '44.98'], ['Colombia', '44.60'], ['United States of America', '32.19'], ['Canada', '3.43'], ['Brazil', '22.72'], ['Italy', '199.34'], ['Indonesia', '144.00'], ['China', '139.54'], ['France', '119.39']]