简体   繁体   中英

Finding element index in nested list

Looking to find the element index of an element in a nested loop.

table = [
    [1, "Y", 3],
    [4, 5, "K"]
]      
for i in range(len(table[0])):
    for j in range(len(table)):
        print(table[i].index("Y"))`

But every time I run the the code it tells me Y is not in my list

You don't need the nested loop. You can loop through the rows and call index() on the row. You can catch the error that will happen when Y is not in the list. This is a Python style of asking forgiveness instead of permission :

for row in table:
    try:
        print(row.index("Y"))
    except ValueError:
        pass

If you just want to know if 'Y' is in the table you can use any() :

any('Y' in row for row in table)
# True

Your inner loop doesn't make any sense; index already covers the entire list; why do you need to do that 3 times?

You will get an error if the item doesn't appear. Instead

for i in range(len(table)):
    if 'Y' in table[i]:
        print(i, table[i].index('Y'))

For each row, you check whether Y appears. If it does, then you print the row and column number where it appears.

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