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

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

提交回复
热议问题