I am new to python and I am trying to create a function that accepts as input a list of lists of integers and returns a sorted version of that list, sorted by the sum of the integers in each sub-list. Below is the code I have thus far. Any suggestions would be great.
def sort_nested_lists (user_list):
for list in user_list
x = sum(user_list))
x = sorted( user_list)
return x
print sort_nested_lists
Here is my new code:
user_list = raw_input("Please enter a list of integers: ")
def sort_nested_lists(user_list):
return sorted(user_list,key = sum)
print sort_nested_lists
Now I get the error:
Please enter a list of integers: [[5,2,7,5],[8,2,6,1],[3,1,8,9,5]]
Any additional help would be great!
You do not have to make it so complicated. Simply use the following one-liner :
return sorted(user_list,key=sum)
That's all. When you specify a key
, sorted(..)
will compare two elements based on the given function it applies to elements in the user_list
. So here it will compare two lists based on the sum of their elements.
To achieve this, you may call the sorted
function with key as sum
>>> my_list = [[1, 6, 3], [2,1,0], [10, 3, 9]]
>>> sorted(my_list, key=sum)
[[2, 1, 0], [1, 6, 3], [10, 3, 9]]
The resultant list will be sorted in increasing order based on the sum of integers in the sub-lists
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.