Smallest element of a sub-list, in a list

Asked

Viewed 89 times

0

I’m trying to apply heuristics to a code that I’ve been working on, but I need to get the smallest element from a sub-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 coordinates x and y (The first two sub-list elements are x and y) and L[ ][2] (Third element) are the values I need to verify. How can I check all the sub-lists, and return the smaller L[ ][2]? That in this example is L[3][2].

  • 1

    It wasn’t very clear what you need to do. What they are x and y? Why the result should be L[3][2]? This value will be the last 1 in the sub-list [2, 1, 1]. That’s right?

  • x e y are the first two values of each sublist, and the result I was looking for was the smallest third element, among all sublists. In that case, the result should be L[3][2], as of all sub-lists, the third element of the fourth sub-list, and the lowest value compared to the others.

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 variable k will store the list index L which contains the smallest third element. As we do not initially know which index, we set the initial index, in this case, 0.

With this we use a repeating structure (for in) to traverse the variable L, where the variable i will receive the sub-list of L, and sublista shall contain the sub-list belonging to L[i].

Having this, just make one if to verify that position 3 of the current sub-list (sublista[2]) is less than position 3 of the sub-list where the index is saved (L[k][2]), if it is smaller, just make sure that k receive the current index value, i.

Browser other questions tagged

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