Andrea Ghezzi Andrea Ghezzi - 1 month ago 9
Python Question

Order tuples in list in python

lst=[('fondamenti', 4, 4), ('googlecode', 1, 1), ('stylesheet', 2, 2), ('javascript', 1, 1), ('inlinemath', 1, 1), ('operazioni', 2, 3), ('permettono', 2, 1), ('istruzioni', 4, 3), ('tantissime', 1, 1), ('parentnode', 1, 1)]


How can I order these tuples in a list?
They should be order by the sum of the occurrences, the result should be this:

lst=[(u'fondamenti', 4, 4), (u'istruzioni', 4, 3), (u'operazioni', 2, 3), (u'stylesheet', 2, 2), (u'permettono', 2, 1), (u'googlecode', 1, 1), (u'inlinemath', 1, 1), (u'javascript', 1, 1), (u'parentnode', 1, 1), (u'tantissime', 1, 1)]

Answer

The sorted builtin has a key option for supplying a function by which to sort. You want to sort on the sum of index 1 and 2. This also needs to be in reversed order.

>>> sorted(lst, key=lambda x: x[1] + x[2], reverse=True)
[('fondamenti', 4, 4),
 ('istruzioni', 4, 3),
 ('operazioni', 2, 3),
 ('stylesheet', 2, 2),
 ('permettono', 2, 1),
 ('googlecode', 1, 1),
 ('inlinemath', 1, 1),
 ('javascript', 1, 1),
 ('parentnode', 1, 1),
 ('tantissime', 1, 1)]

The above is in "interactive session" notation, where I show you the output without assigning to a variable. In real code you would do either of the following:

# Sort and return a new object in the same name.
lst = sorted(lst, key=lambda x: x[1] + x[2], reverse=True)
# Or, sort in-place.
lst.sort(key=lambda x: x[1] + x[2], reverse=True)

Do either of the above, not both.

P.S. Each of the elements is a tuple, not a set.