Making my first steps in Python. I have a list of lists and i'm trying to return the sub list with largest sum of all sub lists. For now I just have the max sum itself. Ex: this code returns 18, but I need to return [3,3,3,3,3,3]
Any directions? Thanks
def find_biggest(lst):
inner_list_sum = []
for i in range(len(lst)):
inner_list_sum.append(sum(lst[i])) # list of elements sums
return max(inner_list_sum) # I actually need the element itself...not the max sum
print(find_biggest([[1,2,3,4], [1,2,3,3], [1,1], [3,3,3,3,3,3]]))
Use max
with key=sum
Ex:
data = [[1,2,3,4], [1,2,3,3], [1,1], [3,3,3,3,3,3]]
print(max(data, key=sum))
Output:
[3, 3, 3, 3, 3, 3]
OK Since I'm not allowed to use (max(data, key=sum)). I did this not very elegant code, but it was accepted a correct answer
def find_biggest(lst):
inner_list_sum = []
for i in range(len(lst)):
inner_list_sum.append(sum(lst[i])) # list of elements sums
max_element=max(inner_list_sum)
seq_index= inner_lis
import functools
def find_biggest(lst):
return functools.reduce(lambda x, y : x if sum(x) > sum(y) else y, lst)
Here, the used lambda
expression is the function equivalent to find the greatest sum and lst
is iterable
.
Please note: reduce
will directly work for python2
, you need to import functools
for python3
only.
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.