Return min/max of multidimensional in Python?

18,706

Solution 1

For the minimum c:

min(c for (a,b,c),(d,e,f) in your_list)

For the maximum c+f

max(c+f for (a,b,c),(d,e,f) in your_list)

Example:

>>> your_list = [[[1,2,3],[4,5,6]], [[0,1,2],[3,4,5]], [[2,3,4],[5,6,7]]]
>>> min(c for (a,b,c),(d,e,f) in lst)
2
>>> max(c+f for (a,b,c),(d,e,f) in lst)
11

Solution 2

List comprehension to the rescue

a=[[[1,2,3],[4,5,6]], [[2,3,4],[4,5,6]]]
>>> min([x[0][2] for x in a])
3

>>> max([x[0][2]+ x[1][2] for x in a])
10

Solution 3

You have to map your list to one containing just the items you care about.

Here is one possible way of doing this:

x = [[[5, 5, 3], [6, 9, 7]], [[6, 2, 4], [0, 7, 5]], [[2, 5, 6], [6, 6, 9]], [[7, 3, 5], [6, 3, 2]], [[3, 10, 1], [6, 8, 2]], [[1, 2, 2], [0, 9, 7]], [[9, 5, 2], [7, 9, 9]], [[4, 0, 0], [1, 10, 6]], [[1, 5, 6], [1, 7, 3]], [[6, 1, 4], [1, 2, 0]]]

minc = min(l[0][2] for l in x)
maxcf = max(l[0][2]+l[1][2] for l in x)

The contents of the min and max calls is what is called a "generator", and is responsible for generating a mapping of the original data to the filtered data.

Solution 4

Of course it's possible. You've got a list containing a list of two-element lists that turn out to be lists themselves. Your basic algorithm is

for each of the pairs
    if c is less than minimum c so far
       make minimum c so far be c
    if (c+f) is greater than max c+f so far
       make max c+f so far be (c+f)

Solution 5

suppose your list is stored in my_list:

min_c = min(e[0][2] for e in my_list)
max_c_plus_f = max(map(lambda e : e[0][2] + e[1][2], my_list))
Share:
18,706
John Smith
Author by

John Smith

Updated on June 25, 2022

Comments

  • John Smith
    John Smith almost 2 years

    I have a list in the form of

    [ [[a,b,c],[d,e,f]] , [[a,b,c],[d,e,f]] , [[a,b,c],[d,e,f]] ... ] etc.
    

    I want to return the minimal c value and the maximal c+f value. Is this possible?

  • John Smith
    John Smith over 12 years
    This seems to work great; thank you! Didn't know you could do it this way (A for B in C format)
  • Charlie Martin
    Charlie Martin over 12 years
    I like it. I'm not sure list comprehensions are the best way to explain it to a beginning, but it's a lovely bit of code.
  • Charlie Martin
    Charlie Martin over 12 years
    Oh, by the way, John, that's the magic term you want for this kind of code: "List comprehension".
  • johnsyweb
    johnsyweb over 12 years
    @CharlieMartin: This is a generator expression, not a list comprehension.