简体   繁体   中英

Find the index of a list element in Python

How could I find a certain index as to where one of the elements is located at within sets. So I would like to find where (2.0, 2.0, 152) is located within the sets list, which is the 5th index. Is there a function that I would be able to use to get to that?

from itertools import groupby
from itertools import accumulate
import itertools

#Configs
Lower = [round(x * 0.5,1) for x in range(4,23)]   #ideal = (4,13) Lower and upper boundary values 
Upper = [round(x * 0.5,1) for x in range(4,23)] # ideal between (10-23)
number = [round(x *0.5,5) for i in range(100, )]    #used for calculations with stand deriv and linear reg
list_set = [Lower, Upper, number]
sets = []
for element in itertools.product(*list_set):
    print(element)
    sets.append(element)

You can use the index -method for that:

sets.index((2.0, 2.0, 152))

The method raises a ValueError if the supplied value is not in the list, which seems to be the case for (2.0, 2.0, 152) .

There are two ways you could go about finding the index of an element from an array in Python.

The first and the most straightforward way to do so is by using the .index() method of any list, which returns the index at which the specified value is located. Take this example:

list = [123, 417, 098]
print(list.index(417))

You can see here that it will print one, because that is the index at which 417 is located in the list array. Though, keep in mind that you might get an error if the specified value doesn't exist.

The second and harder way is by iterating through the array yourself. Take this example:

list = [123, 417, 098]

def findElement(array, element):
    for index in range(len(array)):
        if (array[index] == element):
            return index

print(findElement(list, 417))

What we did here was to define a method which takes as parameters an array and an element, then, iterates through every index of the list, until the value at that index is the specified element. When the values match, it will return the said index. If no values will ever match, it won't return anything.

The advantage of the second approach is the fact that it won't throw an error if there is no such element in the list, however, it is also a bit harder to set up.

try:
    print(sets.index(element))
except:
    print('not found')

If you gonna use more better keep in a dict indexes,which can retrieve you index in O(1) time.Construction can take O(n) time though

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM