Home > Software design >  min and max of nested and multidimensional list in Python
min and max of nested and multidimensional list in Python

Time:05-04

I have a list in form of

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

after finding minimum of c:

I want to return "a" and "b" of the minimal "c "....

my questions are:

question1(important) : I mean after finding minimum of c, how is it possible to return a and b values as Output?

question2: How is it possible to recognized index number of list that contain minimum of c?

thanks.

CodePudding user response:

min accepts a key function. The value you need for every element in your list is at the inner list at index 0 and in this inner list the element at index 2.

data = [[[1, 2, 3], [4, 5, 6]], [[23, 42, 0], [4, 5, 6]], [[-1, -2, 4], [4, 5, 6]]]

item = min(data, key=lambda x: x[0][2])
print(item)

This will give you [[23, 42, 0], [4, 5, 6]].

Now getting the first and the second value from the inner list is easy.

a, b = item[0][:2]
print(a, b)

With the result 23 42.

If you need the index you can simply use i = data.index(item).


An alternative for getting the index would be to add it to the data before you try to find the minimum. enumerate comes in handy here.

item_with_index = min(enumerate(data), key=lambda x: x[1][0][2])
index, item = item_with_index
print(index, item)

The ultra-condensed version:

data = [[[1, 2, 3], [4, 5, 6]], [[23, 42, 0], [4, 5, 6]], [[-1, -2, 4], [4, 5, 6]]]
index, ((a, b, _), _) = min(enumerate(data), key=lambda x: x[1][0][2])
print(index, a, b)

This gives you 1 23 42.

CodePudding user response:

This is a possible solution but it's most likely not the most efficient one. It's useful to understand indexes in lists tho

my_list = [
  [[1,2,3],[4,5,6]],
  [[-1,-2,-3],[7,8,9]],
  [[10,11,12],[-4,-5,6]]
]

minimun = my_list[0][0][2]
temp_mium = my_list[0][0][2]
indexes = [0,1,2]

for i in range(0,len(my_list)):
  for j in range(0,len(my_list[0])):
    for k in range(0,len(my_list[0][0])):
      if k == 2:
        temp_mium = my_list[i][j][k]
      if temp_mium <= minimun:
        minimun = temp_mium
        indexes[0] = i
        indexes[1] = j
        indexes[2] = k

print(minimun)
print(indexes)
  • Related