简体   繁体   中英

sorted function not returning proper result for list of lists

I have a list of lists which I am trying to sort by population density. However, the sorted function doesn't seem to be sorting them properly.

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

This is what's printed onto the console:

> [['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']]

Change your sort function to also convert the element to float , otherwise the item is sorted lexicographically (as strings) instead of numerically

>>> 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']]

You can try sort method :

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

output:

[['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']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM