简体   繁体   中英

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?

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?

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.

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)

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

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