Search code examples
pythonstringfindany

Python - Returning the value if there is an "exact" match?


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 lst[i]
        i+=1

findexact(lst)

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

'a'
'aa'

I would like the result to be:

'a'

What is the right way to use any() to get the right result?


Solution

  • To match your expected output, you cannot use set.intersection as sets are unordered so if you get a as the first item it is totally by chance , you should make key a set and use in,iterating over the list returning the first match which will keep the order:

    def findexact(lst):
        key = {'a','g','t'}
        for ele in lst:
            if ele in key:
                return ele
        return False
    

    If you want to get all the matches and see the non matches just make key a set and use a loop:

    def findexact(lst):
        key = {'a','g','t'}
        for ele in lst:
            if ele in key:
                print(ele)
            else:
                # do whatever
    

    If you want to return a bool based on whether there are any common element use set.isdisjoint:

    def findexact(lst):
        key = {'a','g','t'}
        return not key.isdisjoint(lst)
    

    If there is at least one match, the function will return True, if not then the sets are disjoint so it will return False.

    If you want the index use enumerate:

    def findexact(lst):
        key = {'a','g','t'}
        for ind,ele in enumerate(lst):
            if ele in key:
                return ind, ele
        return False
    

    That will return both the element and the index if we have a match, if you just want the index just return ind, for no match we simply return False