Minimum value of a list within another python list

Asked

Viewed 62 times

0

Hello.

I have a situation I managed to solve by looping. I would like to know if there is any way to simplify what I did, using Arabic or other language resource.

I have a list and within it another list, as below:

import numpy as np

lista=[]
lista.append([0.21, np.array([0.5, 0.5, 0.667]), 2, 0])
lista.append([0.98, np.array([0.7, 0.9, 0.552]), 1, 1])
lista.append([0.05, np.array([0.5, 0.5, 0.552]), 1, 3])
lista.append([1.18, np.array([0.7, 0.9, 0.552]), 1, 0])

need to store in another vector the list that contains the lowest value of the first position, which in this case would be the third list [0.05, np.array([0.5, 0.5, 0.552]), 1, 3]. I did it this way:

mins = lista[0][0]
tmp= lista[0]
vetorfinal =[]
for j in range(len(lista)):
    if lista[j][0] < mins:
        tmp= lista[j]
        mins = lista[j][0]
vetorfinal.append(tmp)

I managed to solve in a way not very usual. I wonder if there is any way to be done with less line of codes.

Thank you!

1 answer

2


Yes, it is possible to use the internal function min, specifying the comparison key (in this case the first element of each sequence):

import numpy as np

lista=[]
lista.append([0.21, np.array([0.5, 0.5, 0.667]), 2, 0])
lista.append([0.98, np.array([0.7, 0.9, 0.552]), 1, 1])
lista.append([0.05, np.array([0.5, 0.5, 0.552]), 1, 3])
lista.append([1.18, np.array([0.7, 0.9, 0.552]), 1, 0])


print(min(lista, key=lambda x: x[0]))
#[0.05, array([0.5  , 0.5  , 0.552]), 1, 3]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.