Find if value exists in multiple lists

后端 未结 4 1302
借酒劲吻你
借酒劲吻你 2021-01-18 18:57

I have 4 list and each element on the list are unique across the 4 list. How do I find if the value exist in one of the list and return which list it exist?

Example

4条回答
  •  别那么骄傲
    2021-01-18 19:29

    Given your updated question, let's assume the a, b, c, d variables are in the global scope

    value = 'a'
    a = ['a','b','c']
    b = ['d','e','f']
    d = ['g','h','i']
    c = ['j','k','l']
    
    w = next(n for n,v in filter(lambda t: isinstance(t[1],list), globals().items()) if value in v)
    print(w)
    

    produces

    a
    

    i.e. the name of the first list in the global namespace that contains value

    If the variables are in a local scope, e.g. within a function, you can use locals() instead

    def f():
        a = ['a','b','c']
        b = ['d','e','f']
        d = ['g','h','i']
        c = ['j','k','l']
        w = next(n for n,v in filter(lambda t: isinstance(t[1],list), locals().items()) if value in v)
        print(w)
    
    f()
    

    produces

    a
    

    Note: you might want to adopt a naming convention to target a specific group of variables, e.g. targ_ as a prefix

    targ_a = ['a','b','c']
    targ_b = ['d','e','f']
    targ_d = ['g','h','i']
    targ_c = ['j','k','l']
    w = next(n for n,v in filter(lambda t: isinstance(t[1],list) and t[0].startswith('targ_'), globals().items()) if value in v)
    print(w)
    

    produces

    targ_a
    

    To explain things a bit more in detail, let's have a look at what the globals() call returns. For example using the python shell

    Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
    [GCC 4.8.4] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> value = 'a'
    >>> targ_a = ['a','b','c']
    >>> targ_b = ['d','e','f']
    >>> targ_d = ['g','h','i']
    >>> targ_c = ['j','k','l']
    >>> globals()
    {'targ_d': ['g', 'h', 'i'], 'targ_c': ['j', 'k', 'l'],
     '__builtins__': ,
     '__doc__': None, '__package__': None,
     '__loader__': ,
     'targ_a': ['a', 'b', 'c'], '__name__': '__main__',
     'targ_b': ['d', 'e', 'f'], '__spec__': None, 'value': 'a'}
    

    as you can see, globals() returns a dictionary. Its keys are the names of the variables defined in the global namespace. Its values are the value held by each such variable.

    Therefore

    >>> next(n for n,v in filter(lambda t: isinstance(t[1],list) and t[0].startswith('targ_'), globals().items()) if value in v)
    'targ_a'
    

    iterates once on the generator produced by the expression, which yields each name in the global namespace that corresponds to a list whose name starts with targ_ and that contains an element equal to value. It does so by iterating on the dictionary returned by the call to globals

提交回复
热议问题