Find the minimum value of a list and print the corresponding index from another list

StackOverflow https://stackoverflow.com/questions/22118524

  •  18-10-2022
  •  | 
  •  

Domanda

Say I have some lists, e.g.

list1 = [9.2,6.6,3.1,6.9]
list2 = [1,2,3,4]

I want to find the minimum value of list1 and take that minimum value's index and use it to print out the value from list2 for that corresponding index.

The min(list1) would give me 3.1, with an index of 2, now i want to print list2[2].

Should note that these are not my actual values, they are much more complicated. I just need the general idea.

È stato utile?

Soluzione

list1, list2 = [9.2,6.6,3.1,6.9], [1,2,3,4]
print list2[min((j,i) for i, j in enumerate(list1))[1]]
# 3

Explanation:

min((j,i) for i, j in enumerate(list1)) will give the smallest element along with its index. In this case, it will return (3.1, 2). So we take only the second element and get the element corresponding to it from list2.

The other way to do the same would be

print min(zip(list1, list2))[1]
# 3

Altri suggerimenti

this should do

print (list2[list1.index(min(list1))])

in long form:

list1 = [9.2,6.6,3.1,6.9]
list2 = [1,2,3,4]
a = min(list1)
b= list1.index(a)  
print (list2[b])

It could be done using index:

list2[list1.index(min(list1))]

Output:

3
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top