Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sort a List by length of value in tuple

I am having difficulty sorting a list of tuples. I would like to sort by the length of a string in the list.

For example:

l = [(99,'bbc', 121),(33,'abcd', 231),(44,'zb', 148), (23,'abcde',221)]

if I sort by element 1:

l.sort(key=itemgetter(1), reverse=True)

This will sort on the alphabetical ranking of the strings, not the length. I would prefer to sort in-place and reverse sort, with longest string first.

I can use a lambda and cmp,

l.sort(lambda x,y: cmp(len(x[1]), len(y[1])), reverse=True)

but is there a more elegant, or pythonic way using key and/or itemgetter?

like image 799
C Mars Avatar asked Nov 01 '13 15:11

C Mars


People also ask

How do you sort a list with a tuple?

Therefore, we can simply use the sort() method to sort a list. First, we will take an unsorted list of tuples and then call the sort() method. The sort() method will change the order from increasing (ascending) to decreasing (descending) when we pass the parameter reverse=True as an argument.

How do you sort a list by length of an element in Python?

Custom Sorting With key= For example with a list of strings, specifying key=len (the built in len() function) sorts the strings by length, from shortest to longest. The sort calls len() for each string to get the list of proxy length values, and then sorts with those proxy values.

How do you sort a list by its length?

Sort the list by passing key to the sort(key = len) method of the list. We have to pass len as key for the sort() method as we are sorting the list based on the length of the string. sort() method will sort the list in place. So, we don't need to store it in new variable.

How do you sort a tuple element in Python?

In Python, use the sorted() built-in function to sort a Tuple. The tuple should be passed as an argument to the sorted() function. The tuple items are sorted (by default) in ascending order in the list returned by the function. We can use a tuple to convert this list data type to a tuple ().


1 Answers

Well you can make the lambda simpler:

l.sort(key=lambda t: len(t[1]), reverse=True)

Also, don't use list as a variable name; it's already taken by a built-in function.

like image 190
arshajii Avatar answered Nov 05 '22 01:11

arshajii