Smallest element of a sub-list, in a list

0

I'm trying to apply heuristics to a code I've been working on right now, but I need to get the smallest element of a list from a list. example:

L = [[1, 1, 6], [1, 2, 5], [1, 3, 7],
     [2, 1, 1], [2, 2, 9], [2, 3, 4],
     [3, 1, 5], [3, 2, 2], [3, 3, 3]]

For each of the sub-lists L [] [0] and L [] [1] are x and y coordinates (The first two elements of the sub-lists are x and y), and the L [] [2] ) are the values I need to check. How can I check all sub-lists, and return the lower L [] [2]? That in this example is L [3] [2].

    
asked by anonymous 30.07.2018 / 02:58

1 answer

2

Code

k = 0
for (i, sublista) in enumerate(L):
    if sublista[2] < L[k][2]:
        k = i
# indice da lista (L) que contem o menor L[][3]
print(k)

Explanation

The k variable will store the index of the L list that contains the smallest third element. Since we do not initially know the index, we will set the initial index, in this case, 0 .

With this we use a repeat structure ( for in ) to go through the L variable, where the i variable will receive the sublist index of L , and sublista will contain the sublist belonging to L[i] .

Having this, just make a if to verify that the current sublist's position 3 ( sublista[2] ) is less than the sub-3 position that we have the index saved ( L[k][2] ), if smaller, cause k to receive the current index value, i .

    
30.07.2018 / 03:45