warrior4223 warrior4223 - 1 month ago 15
Python Question

Returning position of specific symbol in list of lists

For this function I'm writing I want to return the position of a specific character that is closest to the top left of the list of lists. It'd be great to accomplish this in the most basic way without importing modules. Here is the code I have so far then I will explain more about what I'm trying to do

def find_position(symbol,lst):

# Sample List: [['.','M','M','G','G'],
# ['.','.','.','.','h'],
# ['B','B','B','.','h']]
#
for sublist in lst:
for symbol in sublist:
if symbol == True:
lst.find(symbol)
return symbol
else:
return None


So if the function was instructed to find '.' then it should return (0,0) since it is in the first position of the first list. If the function was told to find 'h' then it should return (1,4) since it is in the 4th position (python starts from 0) of the second list. My current code doesn't look for the character closest to the top left as I'm not sure how to program that. Thanks in advance for any help I receive.

Answer

A function that iterates through all elements until it finds the character. As soon as it finds it, it returns the position. To find the psotion you can use the enumerate fucntion which returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence

def find_position(symbol,lst):
    for index, my_list in enumerate(s):
        for i,item in enumerate(my_list):
            if symbol == item:
                return "{},{}".format(index,i)
    return "Not found"    

s = [['.','M','M','G','G'],
              ['.','.','.','.','h'],  
              ['B','B','B','.','h']]
a =  find_position("h",s)