Search code examples
pythonlistcompare

how can I compare two lists in python and if I have matches ~> I want matches and next value from another list


a = [’bww’, ’1’, ’23’, ’honda’, ’2’, ’55’, ’ford’, ’11’, ’88’, ’tesla’, ’15’, ’1’, ’kia’, ’2’, ’3’]

b = [’ford’, ’honda’]

should return all matches and next value from list a

Result -> [’ford’, ’11’, ’honda’, ’2’] or even better [’ford 11’, ’honda 2’]

I am new with python and asking help


Solution

  • Assuming all are in string type also assuming after every name in the list a there will be a number next to him.

    Code:-

    a = ['bww', '1', 'honda', '2', 'ford', '11', 'tesla', '15', 'nissan', '2']
    b = ['ford', 'honda']
    
    res=[]
    for check in b:
        for index in range(len(a)-1):
            if check==a[index]:
                res.append(check+" "+a[index+1])
    print(res)
    

    Output:-

    ['ford 11', 'honda 2']
    

    List comprehension

    Code:-

    a = ['bww', '1', 'honda', '2', 'ford', '11', 'tesla', '15', 'nissan', '2']
    b = ['ford', 'honda']
    
    res=[check+" "+a[index+1] for check in b  for index in range(len(a)-1) if check==a[index]]
    
    print(res) #Same output