Home > database >  Check element in list of lists from items in another list of lists
Check element in list of lists from items in another list of lists

Time:05-31

I have one list of lists list1 and one list to check list2 that I'd like to run a for loop to check if elements from list2 are in list1, then append the element present to 'models' which is a list that pulls the first index from each list in list1.

No errors but I believe it might be because of the types I'm working with.

My scripts:

models = []
for item in cleaned_data:
    if item[0] not in models:
        models.append(item[0])

list1 = [['model1', 'yes', 'TT42'], 
        ['model2', 'yes', 'GG50'],
        ['model3', 'no', 'BB12']]

list2 = ['TT42', 'GG50', 'BB12']

...
models = ['model1', 'model2', 'model3']
...

for item in list1:
    if item == list2:
        models.append(item)
print(models)

OUTPUT> ['model1', model2', 'model3']

EXPECTED> [['model1', 'TT42'], ['model2', 'GG50'], ['model3', 'BB12']

CodePudding user response:

IIUC this will take your list 2 and compare it to your list 1 and find where all anything from list2 is equal to anything from list1 and add it to the models list

list1 = [['model1', 'yes', 'TT42'], 
        ['model2', 'yes', 'GG50'],
        ['model3', 'no', 'BB12']]

list2 = ['TT42', 'GG50', 'BB12']

single_list = [list1[x][y] for x in range(0, len(list1)) for y in range(0, len(list1[x]))]

models = [x for x in list2 for y in single_list if x ==y]
models

If this is not the expected results please provide more details and expected results.

CodePudding user response:

There are some issues with your code.

Your loop doesn't do anything, because when you do:

if item == list2:

The comparison will always be false, as the structure of item and list2 are different (e.g. you're comparing ["model1", "yes", "TT42"] with ['TT42', 'GG50', 'BB12']).

Your output is ['model1', model2', 'model3'] but it is because you defined it as such, the loop didn't change it.

Also, when you do:

models.append(item)

You were going to add a whole list inside the models variable. For instance, if the first comparison of the loop was correct, you'd have:

>>> print(models)
['model1', model2', 'model3', ['model1', 'yes', 'TT42']]

And it's obviously not what you want.


Here's a way of doing what you want:

list1 = [['model1', 'yes', 'TT42'], 
        ['model2', 'yes', 'GG50'],
        ['model3', 'no', 'BB12']]

list2 = ['TT42', 'GG50', 'BB12']
models = [[item[0], item[2]] for item in list1 if item[2] in list2]

Output:

>>> print(models)
[['model1', 'TT42'], ['model2', 'GG50'], ['model3', 'BB12']]
  • Related