Palpa
Palpa

Reputation: 21

Get min max from the list inside a list

I am new to Python. I am trying to get min and max (output as list) of a list inside a list. But it is not working as expected. Here is what I have so far.

import functools

# Input
raw_data = [
    [2, 2, 3, 4, 5, 6, 7],
    [0, 2, 3, 4, 5, 6, 17],
    [3, 4, 3, 4, 5, 6, 37]
]

min_max_rows = list(map(lambda x: (min(x), max(x)), raw_data))
result = functools.reduce(lambda x, y: (min(x), max(y)), min_max_rows)

print(result) # Prints (2,37) instead of (0,37)

Upvotes: 2

Views: 138

Answers (4)

Aguy
Aguy

Reputation: 8059

This might be closer to what you want:

result = functools.reduce(lambda a, b: (min(*a, *b), max(*a, *b)), min_max_rows)

Have the max and min function evaluate explicitly on two arguments which are your tuples from the list. the * is needed to unpack the tuples.

Upvotes: 0

Prasanna
Prasanna

Reputation: 4636

Use this

min_val = min(min(raw_data))
max_val = max(max(raw_data))
min_max_list = [min_val,max_val]

Edit:

There is a problem with this which I apparently overlooked. The min_val contains the minimum value of that row that starts with the smallest value. Likewise for max_val so instead, I propose a different solution

temp1 = []
temp2 = []
for x in raw_data:
    temp1.append(min(x))
    temp2.append(max(x))
min_max_list = [min(temp1),max(temp2)]

Upvotes: 2

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

NumPy approach - it should be much faster on bigger lists:

import numpy as np

In [74]: a = np.asarray(raw_data)

In [75]: a
Out[75]:
array([[ 2,  2,  3,  4,  5,  6,  7],
       [ 0,  2,  3,  4,  5,  6, 17],
       [ 3,  4,  3,  4,  5,  6, 37]])

In [76]: min_max_list = [a.min(), a.max()]

In [77]: min_max_list
Out[77]: [0, 37]

Upvotes: 1

nalzok
nalzok

Reputation: 16107

You can flatten your list of list first:

flat = [item for sublist in raw_data for item in sublist]
max_item = max(flat)
min_item = min(flat)

Upvotes: 3

Related Questions