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

后端 未结 6 611
陌清茗
陌清茗 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 05:58
    def intersect(a, b):
      return list(set(a) & set(b))
    
    print intersect(b1, b2)
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-13 06:01

    do like this:

    [e for e in a if e in b]

    0 讨论(0)
  • 2021-01-13 06:10

    Use sets: https://docs.python.org/2/library/sets.html

    result = set(list1) & set(list2)
    

    if you want to make it a conditional like any:

    if (set(list1) & set(list2)):
        do something
    
    0 讨论(0)
  • 2021-01-13 06:13

    Yes, it is possible, by using a filter when doing your list comprehension :

    list1 = ['a', 'b', 'c', 'd', 'e']
    list2 = ['g', 'z', 'b', 'd', '33']
    [elem for elem in list1 if elem in list2]
    # ['b', 'd']
    
    0 讨论(0)
  • 2021-01-13 06:19

    Use a list comprehension:

    [elem for elem in list1 if elem in list2]
    

    Example:

    list1 = [1, 2, 3, 4, 5]
    list2 = [1, 10, 2, 20]
    
    c = [elem for elem in list1 if elem in list2]
    print(c)
    

    Output

    [1, 2]
    
    0 讨论(0)
提交回复
热议问题