简体   繁体   中英

How do I get the list in which an element is in?

Say I have two lists:

L1 = [a, b, c, d]

and

L2 = [e, f, g, h]

where the letters can be of any type (it does not make a difference).

Is there a way to ask Python : "Which list ( L1 and/or L2 ) contains the element 'a' (or any other element), and have it return the name of that list?

In order to achieve this, better data-structure will be using a dict . For example:

my_list_dict = {
    'L1': ['a', 'b', 'c', 'd'],
    'L2': ['e', 'f', 'g', 'h']
}

Then you may create a custom function to achieve your task as:

def find_key(c):
    for k, v in my_list_dict.items():
        if c in v:
            return k
    else:
        raise Exception("value '{}' not found'.format(c))

Sample run:

>>> find_key('c')
'L1'
>>> find_key('g')
'L2'

check using :

if 'a' in l1:
    print "element in l1" #or do whatever with the name you want
elif 'a' in l2:
    print "element in l2"
else:
    print "not in any list"

Or use a function like :

def ret_name(c,l1,l2):
    if c in l1:
        return 1
    elif c in l2:
        return 2
    else:
        return 0
x=ret_name('a',l1,l2)
#and check if x=1 or x=2 or x=0 and you got your ans.

This will do given that we are limited to L1 and L2 only.

def contains(elem):
    return 'L1' if elem in L1 else 'L2'

For flexibility, you can pass the lists as a list of tuples (list object, list name in string) .

>>> contains(a, [(L1, 'L1'), (L2, 'L2')])
>>> 'L1'

Take note that in case of multiple lists having the element ( elem ), the function will return the first one supplied in tups based on order.

def contains(elem, tups):
    for tup in tups:
        if elem in tup[0]: // list object
            return tup[1]  // list name

    return 'Not found'

Although not encouraged, you could dynamically get the names of lists if they are defined as variables in your program by filtering through globals() .

L1 = ['a', 'b', 'c', 'd']
L2 = ['e', 'f', 'g', 'h']

has_a = [k for k, l in globals().items() if isinstance(l, list) and 'a' in l]

print(has_a)
# ['L1']

This is my solution and I find it to be quite nice :)

L1,L2 = ['a', 'b', 'c', 'd'],['e','f','g','h']
n = input('Enter a letter: ')
while True:
      if n in L1:
            print('Letter %s is contained inside L1 list!' %(n))
            break
      else:
            print('Letter %s is contained inside L2 list!' %(n))
            break

I hope it helps happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM