Find if value exists in multiple lists

后端 未结 4 1304
借酒劲吻你
借酒劲吻你 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:34

    you can use list comprehension:

    >>> value ="a"
    >>> a = ['a','b','c']
    >>> b = ['d','e','f']
    >>> d = ['g','h','i']
    >>> c = ['j','k','l']
    >>> [x for x in a,b,c,d if value in x]
    [['a', 'b', 'c']]
    

    To get variable name:

    >>> for x in a,b,c,d:
    ...     if value in x:
    ...         for key,val in locals().items():
    ...             if x == val:
    ...                 print key
    ...                 break
    ... 
    a
    

    locals() contains local scope variable as dictionary, variable name being key and its value being value

    globals contains global scope variable as dictionary, variable name being key and its value being value

提交回复
热议问题