Home > Net >  Get Specific Element from a 2d List Using Condition
Get Specific Element from a 2d List Using Condition

Time:12-22

Here is a list.

list=[[[5, 1, 50], [7, 10, 52], 2], [[7, 10, 52], [10, 5, 163], 3], [[10, 5, 163], [13, 9, 85], 3], [[13, 9, 85], [14, 3, 176], 1], [[14, 3, 176], [15, 7, 96], 1]]

I want to retrieve an element from the list based on the minimum value which are 2,3,3,1,1 or we can say list[i][j]. From these element I want to find the minimum which is 1 and from that I want to retrieve the element [[[13, 9, 85], [14, 3, 176], 1]]. As here two 1 exist, indexwise I am choosing first one.

Can you tell me how can I do the code? Sorry for being noob.

CodePudding user response:

Just use find minimum concept with O(N)

list1=[[[5, 1, 50], [7, 10, 52], 2], [[7, 10, 52], [10, 5, 163], 3], [[10, 5, 163], [13, 9, 85], 3], [[13, 9, 85], [14, 3, 176], 1], [[14, 3, 176], [15, 7, 96], 1]]

# Assign first element as a minimum.
min1 = list1[0][2]
minIx = 0;

for i in range(len(list1)):

    # If the other element is min than first element
    if list1[i][2] < min1:
        min1 = list1[i][2] #It will change
        minIx = i

print("The smallest element in the list is ",list1[minIx])
  • Related