How can i sort a list of tuples by one of it's values and then the other? [duplicate]

谁说我不能喝 提交于 2019-12-04 07:00:54

问题


I'll get to the point,i have this:

    ocurrencias = [('quiero', 1), ('aprender', 1), ('a', 1), ('programar', 1), ('en', 1), ('invierno', 2), ('hace', 1), ('frio', 1), ('este', 1)]

I want to sort it by the second value of the tuples and then by their string value and then print every element to get this:

    output:invierno 2
           a 1
           aprender 1
           en 1
           este 1
           frio 1
           hace 1
           programar 1
           quiero 1

Don't know if i'm making it clear enough,but i'm not really proficient at english so forgive me.

Thanks in advance


回答1:


Use sorted with a key which makes a reversed version of each tuple, to sort the second value in descending order, you can add a - in front to negate the value:

sorted(ocurrencias, key = lambda x: (-x[1], x[0]))
# [('invierno', 2), ('a', 1), ('aprender', 1), ('en', 1), ('este', 1), ('frio', 1), ('hace', 1), ('programar', 1), ('quiero', 1)]

As commented by @Jonathon, the reason this works is due to the fact that lists and tuples comparison happens in order i.e, compare the first element; if not equal then the second element, to see more about object comparison in python.



来源:https://stackoverflow.com/questions/41603482/how-can-i-sort-a-list-of-tuples-by-one-of-its-values-and-then-the-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!