niamleeson
niamleeson

Reputation: 189

Get the index of the exact match from a list

lst = ['a', 'b', 'c', 'aa', 'bb', 'cc']

def findexact(lst):
    i=0
    key = ['a','g','t']
    while i < len(lst):
        if any(item in lst[i] for item in key):
            print i

        i+=1

findexact(lst)

in the above code, the result comes out to be:

0
3

I would like the result to be:

0

I would like to get the index of the "exact" match. What do I need to do to get the acceptable result?

Upvotes: 1

Views: 6639

Answers (4)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

You can use enumerate with a gen exp,calling next with a default value to catch where you have no common elements:

def findexact(lst):
    key = {'a','g','t'}
    return next((ind for ind,ele in enumerate(lst) if ele in key), None)
lst = ['a', 'b', 'c', 'aa', 'bb', 'cc']
match = findexact(lst)
if match is not None:
  print(match)
0

This is O(n) as set lookups are O(1), in the worst case we look at every element in lst, for large amounts of data, using list.index or having keys as a list and using in is not going to scale well

Upvotes: 0

shuttle87
shuttle87

Reputation: 15934

Just change in to == and make the test a bit different like follows:

lst = ['a', 'b', 'c', 'aa', 'bb', 'cc']

def findexact(lst):
    key = ['a','g','t']
    for idx, elem in enumerate(lst):
        if any(item == elem for item in key):
            print idx

findexact(lst)

Note here that I'm iterating over lst directly and getting the index from enumerate. This is a more pythonic way of doing it than introducing a variable i that just keeps track of the index. You can condense this further as the one liners in other answers show.

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49318

Just use index(). This tells you the index of the given item in the given list. If it's not present, it produces an error, which we will catch.

lst = ['a', 'b', 'c', 'aa', 'bb', 'cc']

def findexact(lst):
    keys = ['a','g','t']
    for key in keys:
        try:
            return lst.index(key)
        except ValueError:
            pass

print findexact(lst)

Upvotes: 0

mrcheshire
mrcheshire

Reputation: 535

Try changing if any(item in lst[i] for item in key): to this:

if any(item == lst[i] for item in key):

You were getting multiple results because 'a' is in 'aa' but 'a' is not == to 'aa'.

Does that give you the behavior you want?

Upvotes: 3

Related Questions