Reputation: 1243
I have nested list and I am trying to find out better approach to find list has largest sum of values.
Below is my nested list:
nums = [[[1, 3000], [1, 2000]],
[[1, 3000], [2, 3000]],
[[1, 3000], [3, 4000]],
[[2, 5000], [1, 2000]],
[[2, 5000], [2, 3000]],
[[2, 5000], [3, 4000]],
[[3, 4000], [1, 2000]],
[[3, 4000], [2, 3000]],
[[3, 4000], [3, 4000]]]
Desired output = [[2, 5000], [3, 4000]]
since sum of values largest.
My approach:
largest = []
for i in range(len(nums)-1):
if (nums[i][0][1] + nums[i][1][1]) > (nums[i+1][0][1] + nums[i+1][1][1]):
largest.append(nums[i])
print(largest)
Upvotes: 2
Views: 269
Reputation: 10460
A variation of Transhuman's answer:
print max(nums, key=lambda l: sum(l[0] + l[1]))
Upvotes: 0
Reputation: 42411
DATA = [
[[1, 3000], [1, 2000]],
[[1, 3000], [2, 3000]],
[[1, 3000], [3, 4000]],
[[2, 5000], [1, 2000]],
[[2, 5000], [2, 3000]],
[[2, 5000], [3, 4000]],
[[3, 4000], [1, 2000]],
[[3, 4000], [2, 3000]],
[[3, 4000], [3, 4000]],
]
tups = [
(sum(n for _, n in row), row)
for row in DATA
]
mx = max(tups)
print(mx) # (9000, [[2, 5000], [3, 4000]])
print([xs[0] for xs in mx[1]]) # [2, 3]
Upvotes: 4
Reputation: 57033
Sort the elements using the sum as the key:
max(DATA, key=lambda x:x[0][1] + x[1][1])
#[[2, 5000], [3, 4000]]
This is the fastest solution for the posted data.
Upvotes: 2
Reputation: 164613
Here's one way using max
and a custom function:
from operator import itemgetter
res = max(nums, key=lambda x: sum(map(itemgetter(1), x)))
[[2, 5000], [3, 4000]]
Upvotes: 2
Reputation: 3547
One way is using:
max(nums, key=lambda x:sum(list(zip(*x))[1]))
#[[2, 5000], [3, 4000]]
Upvotes: 1