1

I have got the hang of sorting a list of tuples by their second elements when that element is just a solo integer, but something about the second elements being lists of integers is throwing me. for example with the following list...

[("Jack", [1,2,5,3]), ("Anna", [7,8,5,2]), ("Ryan", [1,2,1,1])]

... I am trying to sort the list of tuples into ascending order based on the sums of the lists within each (so as to produce the following outcome in this example)...

[("Ryan", [1,2,1,1]), ("Jack", [1,2,5,3]), ("Anna", [7,8,5,2])]

Thanks

edit: My question differs from Sort a list of tuples by 2nd item (integer value) because mine refers specifically to the case in which the second element is a list, which is where my stumbling block was. Thanks for helpful replies so far.

Community
  • 1
  • 1
cmorga1
  • 91
  • 1
  • 7

2 Answers2

4

You could use the key attribute of the sort function

Code:

check = [("Jack", [1, 2, 5, 3]), ("Anna", [7, 8, 5, 2]), ("Ryan", [1, 2, 1, 1])]
sorted(check, key=lambda x: sum(x[1]))

Output:

[('Ryan', [1, 2, 1, 1]), ('Jack', [1, 2, 5, 3]), ('Anna', [7, 8, 5, 2])]

Notes:

  • First I created a list check
  • The sorted function is used to create a sorted list
  • The key attribute is passed with sum to sort by the sum of the list in the tuple

For a more robust method you could use the below method

Code1:

check = [("Jack", [1, 2, 5, 3]), ("Anna", [7, 8, 5, 2]), ("Ryan", [1, 2, 1, 1])]
def validator(lst):
    if isinstance(lst,list):
        return sum(lst)
    else:
        return lst
print sorted(check, key=lambda x: validator(x[1]))

Output:

[('Bad', 2), ('Ryan', [1, 2, 1, 1]), ('Jack', [1, 2, 5, 3]), ('Anna', [7, 8, 5, 2])]
Community
  • 1
  • 1
The6thSense
  • 8,103
  • 8
  • 31
  • 65
1

You can provide a function to key in sorted:

L = [("Jack", [1,2,5,3]), ("Anna", [7,8,5,2]), ("Ryan", [1,2,1,1])]
sorted(L, key=lambda x: sum(x[1])) 
[('Ryan', [1, 2, 1, 1]), ('Jack', [1, 2, 5, 3]), ('Anna', [7, 8, 5, 2])]

This func = lambda x: sum(x[1]) is equivalent to:

def func(x):
    return sum(x[1])

Now you can use func instead of the lambda expression:

sorted(L, key=func) 

The return value of this function, i.e. the sum of the second element in the tuple will be used as sorting criterion.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161