In nested list find list has largest sum sum of values

Viewed 231

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)
5 Answers
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]

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]]

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.

One way is using:

max(nums, key=lambda x:sum(list(zip(*x))[1]))
#[[2, 5000], [3, 4000]]

A variation of Transhuman's answer:

print max(nums, key=lambda l: sum(l[0] + l[1]))
Related