warrior4223 warrior4223 - 1 year ago 69
Python Question

Returning index of list in list of lists that contains a specific string

I think I'm close with this function but I'm having trouble. I need to return the index of the list in a list of lists that contains a particular string. For example, if the list of lists was [['.','c','e','g'],['d',h','t','f']] and my goal was to look for 'c' then the function would need to return 0 since it is in the first list. Or if the goal was to look for 'h' it would return 1 since it is in the second list.

Here is the code I have so far:

def which_one(lst):
for row in lst:
for col in lst:
if col == 'c':
return col

Answer Source

Consider a different approach that avoids using two loops. Making use of enumerate on your list will only require you to iterate once, where each iteration you will have two values, each representing a running count representing your index, and the next your value. You simply check the character you are interested against the value using in, and return the index. Observe the example:

def find_index(l, c):
    for i, v in enumerate(l):
        if c in v:
            return i

res = find_index([['.','c','e','g'],['d', 'h','t','f']], 'c')

print(res) # 0

res = find_index([['.','c','e','g'],['d', 'h','t','f']], 't')

print(res) # 1

Just for the sake of adding it, if you wanted to collect all indexes for the character you are looking up, this can be done in a comprehension:

def all_indexes(l, c):
    return [i for i, v in enumerate(l) if c in v]


res = all_indexes([['.','c','e','g'],['d', 'h','t','f', 'c']], 'c')

print(res) # [0, 1]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download