Search code examples
pythonlistfor-looplist-comprehension

Make new list from source list at index 0, find matching items in second list and append to that new list at index 1


I have a scrip that I'd like to take source data list1 and pull data from it. models is a list that contains index[0] of each item in list1 and now I'd like to append or insert a specific item from list1 if it's found in list2, to the first index to produce something like the below. Note the items I want to match from list2 wont always be in the same index found in list1.

models = [['model1', 'TT42'], ['model2', 'GG50'], ['model3', 'BB12']]

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

models = []
for item in list1:
    if item[0] not in models:
        models.append(item[0])
#  models = ['model1', 'model2', 'model3']

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

for item in list1:
    for element in item:
        if element in list2:
            models.insert(1, element)
print(models)
#  models = [model1, TT42, TT42, TT42, model2. model3]
#  what am I missing?


Solution

  • You're making a list of strings. It looks like your intent with the insert function is to insert into a list, but the object is a string, and that won't create a 2D list like you intend. I think this fixes your code. Note that I appended a list, making a 2D list as desired:

    list1 = [['model1', 'yes', 'TT42'], 
            ['model2', 'yes', 'GG50'],
            ['model3', 'no', 'BB12']]
    
    list2 = ['TT42', 'GG50', 'BB12']
    
    model = []
    
    for item2 in list2:
        for row in list1:
            if item2 in row:
                model.append([row[0],item2])
    
    print(model)