Finding if any element in a list is in another list and return the first element found

后端 未结 6 614
陌清茗
陌清茗 2021-01-13 05:23

It is easy to check if an element of a list is in another list using any():

any(elem in list2 for elem in list1)

but is there

6条回答
  •  说谎
    说谎 (楼主)
    2021-01-13 06:01

    This answer is similar to an answer on a similar question, where @jamylak goes into more detail of timing the results compared to other algorithms.

    If you just want the first element that matches, use next:

    >>> a = [1, 2, 3, 4, 5]
    >>> b = [14, 17, 9, 3, 8]
    >>> next(element for element in a if element in b)
    3
    

    This isn't too efficient as it performs a linear search of b for each element. You could create a set from b which has better lookup performance:

    >>> b_set = set(b)
    >>> next(element for element in a if element in b_set)
    

    If next doesn't find anything it raises an exception:

    >>> a = [4, 5]
    >>> next(element for element in a if element in b_set)
    Traceback (most recent call last):
    StopIteration
    

    You can give it a default to return instead, e.g. None. However this changes the syntax of how the function parameters are parsed and you have to explicitly create a generator expression:

    >>> None is next((element for element in a if element in b_set), None)
    True
    

提交回复
热议问题