Check whether an item in a list exist in another list or not python

后端 未结 3 891
别那么骄傲
别那么骄傲 2021-01-13 13:55

There are 2 list

a= [1,2,3]
b = [1,2,3]

Now I want to check whether an element from a exist in b or not in pytho

相关标签:
3条回答
  • 2021-01-13 14:02

    I think you should use sets. This is the way you can do it:

    def check_element(a, b):
      return not set(a).isdisjoint(b)
    
    0 讨论(0)
  • 2021-01-13 14:06

    bool(set(a)&set(b)) converts a and b into sets and then applies the intersection operator (&) on them. Then bool is applied on the resulting set, which returns False if the set is empty (no element is common), otherwise True (the set is non-empty and has the common element(s)).

    Without using sets: any(True for x in a if x in b). any() returns True if any one of the elements is true, otherwise False.

    0 讨论(0)
  • 2021-01-13 14:19
    len(set(a+b)) < len(set(a)) + len(set(b))
    
    0 讨论(0)
提交回复
热议问题