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

后端 未结 6 637
陌清茗
陌清茗 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: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]
    

提交回复
热议问题