简体   繁体   中英

Index of a list in a nested for loop in python

I have a nested loop. I want to iterate on a list of lists and check if a parameter is in a list, bring me back the list index.

parameter="Abcd"
li1=["ndc","chic"]
li2=["Abcd","cuisck"]
Li=[li1,li2]
for i in Li:
    for j in i:
        if (parameter==j):
            x=i+1
print(x)

I expect an integer like for this example x=2. But it does not work. How can I do that?

Use enumerate , which returns the index and the element. Also use sets , which are faster than lists (for long lists).

parameter = "Abcd"
lst1 = ["ndc", "chic"]
lst2 = ["Abcd", "cuisck"]
lst = [lst1, lst2]
x = None

for i, sublst in enumerate(lst):
    if parameter in set(sublst):
        x = i+1
print(x)
# 2       

You didn't specify the output you are expecting, but I think you want something like this:

parameter="Abcd"
li1=["ndc","chic"]
li2=["Abcd","cuisck"]
Li=[li1,li2]
for row in Li:
    for i, j in enumerate(row):
        if parameter == j:
            print("List", Li.index(row),"Element", i)

Output:

List 1 Element 0

Use numpy array. It will save you tons of time and cost.

Li = np.array([li1,li2])

Li == parameter

array([[False, False],
       [ True, False]])

row, column = np.where(Li == parameter)

row
Out[17]: array([1], dtype=int64)
parameter="Abcd"
li1=["ndc","chic"]
li2=["Abcd","cuisck"]
Li=[li1,li2]

index = -1

for i in Li:
    if parameter in i:
        index = Li.index(i)
            
print(index)

You can check if something is in a list with 'in' and get the index of the element with .index, it returns the integer position in the list. Perhaps you want a tuple for the nested position ? use something like (Li.index(i), i.index(parameter)) as your return value. Don't forget to declare your return value outside your loop scope !

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