how to search for a list in a list of lists in python

Question:

I have this list:


t = [['1', '0', '1', '0', '0', '0', 'up', 5], ['1', '0', '1', '0', '0', '1', 'up', 5], ['1', '0', '1', '0', '1', '0', 'down', 5]]

I want to be able to find the following from that list:

o = ['1', '0', '1', '0', '1', '0']
u = "up"
y = "down

to make it clearer, i want to find out if o exists in t, and to find out whether or not u exists in the sublist where o exists

i tried :


t = [['1', '0', '1', '0', '0', '0', 'up', 5], ['1', '0', '1', '0', '0', '1', 'up', 5], ['1', '0', '1', '0', '1', '0', 'down', 5]]
o = ['1', '0', '1', '0', '1', '0']
u = "up"

if o and u in t:
    print("the list you're looking for is present and the position of that sublist is up")
elif o and y in t:
    print("the list you're looking for is present and the position of that sublist is down")
else:
    print("it's not there")

i get this result:

it's not there

what i am trying to get is:

the list you're looking for is present and the position of that sublist is down.

Asked By: damian2345673

||

Answers:

When you use in, Python will check if the entire object in an element of the list, whereas you are only searching for an element that begin with o.

You could for instance do something like :

matching_sub_list = None
for sub_list in t:
    if sub_list[:len(o)] == o: # Check if the first elements of sub_list are the same as the elements of o
        matching_sub_list = sub_list
        break # This assumes there is only one list that matches

if matching_sub_list is None:
    print("it's not there")
else:
    if u in matching_sub_list:
        print("the list you're looking for is present and the position of that sublist is up")
    elif y in matching_sub_list:
        print("the list you're looking for is present and the position of that sublist is down")

But I would recommand to rethink your date structure, and maybe store the sub_lists in t in another way, such as 2 lists of lists : one containing the elements, and one containing the up/down and the following number. You could also create a class dedicated to holding those values, with custom function to check, etc…

Answered By: charon25

Assuming the number of ‘1’, ‘0’s are fixed in each sublist and is a smaller number like 6 as in your example, its not too much to ask to build a look up set like:

look_up = {(''.join(a[:6]), a[6]) for a in t}

and then use that to look up like:

if (''.join(o), u) in look_up:
    print("up")
elif (''.join(o), y) in look_up:
    print("down")

For your example it should print "down".

Answered By: SomeDude
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.