简体   繁体   中英

Searching for an item in a nested list and then returning the index of an item

So I was trying to write a function called find_treasure which takes a 2D list as a parameter. The purpose of the function is to search through the 2D list given and to return the index of where the 'x' is located.

def find_treasure(my_list):

    str1 = 'x'
    if str1 in [j for i in (my_list) for j in i]:
    index = (j for i in my_list for j in i).index(str1)
    return(index)


treasure_map = [[' ', ' ', ' '], [' ', 'x', ' '], [' ', ' ', ' ']]

print(find_treasure(treasure_map))

However, I can't seem to get the function to return the index, I tried using the enumerate function too but either I was using it wrongly.

Using enumerate

def find_treasure(my_list):
    str1 = 'x'
    for i,n  in enumerate(my_list):
        for j, m in enumerate(n):
            if m == str1:
                return (i, j)

treasure_map = [[' ', ' ', ' '], [' ', 'x', ' '], [' ', ' ', ' ']]
print(find_treasure(treasure_map))

Output:

(1, 1)

Using index function.

def find_treasure(my_list):
    str1 = 'x'
    for i,n  in enumerate(my_list):
        try:
          return (i, n.index(str1))
        except ValueError:
          pass

treasure_map = [[' ', ' ', ' '], [' ', 'x', ' '], [' ', ' ', ' ']]
print(find_treasure(treasure_map))

Output

(1, 1)

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