How to check if one of the following items is in a list?

前端 未结 14 2092
终归单人心
终归单人心 2020-11-22 17:02

I\'m trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the

相关标签:
14条回答
  • 2020-11-22 17:56

    I have to say that my situation might not be what you are looking for, but it may provide an alternative to your thinking.

    I have tried both the set() and any() method but still have problems with speed. So I remembered Raymond Hettinger said everything in python is a dictionary and use dict whenever you can. So that's what I tried.

    I used a defaultdict with int to indicate negative results and used the item in the first list as the key for the second list (converted to defaultdict). Because you have instant lookup with dict, you know immediately whether that item exist in the defaultdict. I know you don't always get to change data structure for your second list, but if you are able to from the start, then it's much faster. You may have to convert list2 (larger list) to a defaultdict, where key is the potential value you want to check from small list, and value is either 1 (hit) or 0 (no hit, default).

    from collections import defaultdict
    already_indexed = defaultdict(int)
    
    def check_exist(small_list, default_list):
        for item in small_list:
            if default_list[item] == 1:
                return True
        return False
    
    if check_exist(small_list, already_indexed):
        continue
    else:
        for x in small_list:
            already_indexed[x] = 1
    
    0 讨论(0)
  • 2020-11-22 17:57
    >>> L1 = [2,3,4]
    >>> L2 = [1,2]
    >>> [i for i in L1 if i in L2]
    [2]
    
    
    >>> S1 = set(L1)
    >>> S2 = set(L2)
    >>> S1.intersection(S2)
    set([2])
    

    Both empty lists and empty sets are False, so you can use the value directly as a truth value.

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