How to check if a value in one list is in another list with a one-liner for an if statement in Python if I'm not using sets?

前端 未结 3 742
别那么骄傲
别那么骄傲 2020-12-21 04:39

I\'m trying to construct a one liner that would check if any of the values in one list are present in another list and return True or False if it does or does not.

T

相关标签:
3条回答
  • 2020-12-21 05:19

    You can us an any(..) builtin function with a generator expression:

    any(e in list2 for e in list1)
    

    So this will check if there is at least one element that occurs in both lists.

    Note however that this will result in a worst-case O(n2) algorithm. If the elements are hashable for instance, and you can use a set, we can make it an O(n) average-case algorithm.

    0 讨论(0)
  • 2020-12-21 05:22

    You could also do

    set(list1).intersection(list2)
    

    to get the set of elements that occur in both; the length of the set is 0 if there's no intersection, otherwise positive. You can treat this set as a boolean, since Python evaluates empty sets to False and nonempty sets to True.

    if set(list1).intersection(list2):
        print ('Lists have elements in common')
    else: 
        print ('No elements in common')
    

    Runtime is O(n) average-case, O(n^2) worst-case: https://wiki.python.org/moin/TimeComplexity

    0 讨论(0)
  • 2020-12-21 05:25

    Supose we have this lists:

    list1 = ['bar', 'foo', 'qwerty', 9, 1]
    list2 = [1, 2, 3, 'foo']
    

    If we want to see the repeated values:

    [i for i in list1 if i in list2]
    

    The input:

    ['foo', 1]
    

    If we want True false:

    (map(lambda each: each in list1, list2))
    

    The input:

    [True, False, False, True]
    

    The input is checking list2, the first value '1' exists in list1 and the last 'foo' too.

    0 讨论(0)
提交回复
热议问题