maybeyourneighour
maybeyourneighour

Reputation: 494

how to append the list with the biggest difference between it's items

I have a list with lists with lists and for each list in list1 the one list with the biggest difference between the numbers has to be added to a new list.

list1 = [ [ [3, 5], [3, 8], [4, 10] ], [ [2, 4], [4, 6], [7, 12], [12,14] ] ]
wanted_output = [ [4, 10], [7, 12] ]

I tried this, but don't know how to continue.

for item in list1:
        for pair in item:
              max_diff = pair[1] - pair[0]

Upvotes: 1

Views: 48

Answers (3)

Mo7art
Mo7art

Reputation: 303

That is an easy solution I think:

wanted_output = []
for item in list1:
    max_diff = 0
    temp = None
    for pair in item:
        if pair[1] - pair[0] > max_diff:
            max_diff = pair[1] - pair[0]
            temp = pair
    wanted_output.append(temp)


Upvotes: 1

CDJB
CDJB

Reputation: 14506

You can do this using a combination of max() with a lambda and a list-comprehension:

>>> list1 = [ [ [3, 5], [3, 8], [4, 10] ], [ [2, 4], [4, 6], [7, 12], [12,14] ] ]
>>> [max(l, key=lambda x: abs(x[0]-x[1])) for l in list1]
[[4, 10], [7, 12]]

Alternatively, as a written out function using a for-loop:

rv = []

for l in list1:
    max_seen = -float('inf')
    max_pair = []
    for p in l:
        if abs(p[0] - p[1]) > max_seen:
            max_seen = abs(p[0] - p[1])
            max_pair = p
    rv.append(max_pair)

Which gives us

>>> rv
[[4, 10], [7, 12]]

Upvotes: 1

yatu
yatu

Reputation: 88236

You can use a list comprehension to iterate over the inner lists, and use max with a key, to specify that you want to keep the sublist with the maximum differece between its elements:

[max(l, key=lambda sl: abs(sl[0]-sl[1])) for l in list1]
# [[4, 10], [7, 12]]

Upvotes: 2

Related Questions