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

Question:

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

Asked By: KariLai

||

Answers:

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
Answered By: Yash Mehta

Here is a neat one-liner to solve what you are looking for. It uses a list comprehension, which iterates over 2 items (bi-gram) of the list at once and then combines the matching items with their next item using .join()

[' '.join([i,j]) for i,j in zip(a,a[1:]) if i in b]  #<------
['honda 2', 'ford 11']

EXPLANATION:

  1. You can use zip(a, a[1:]) to iterate over 2 items in the list at once (bi-gram), as a rolling window of size 2. This works as follows.

enter image description here

  1. Next you can compare the first item i[k] in each tuple (i[k],i[k+1]) with elements from list b, using if i in b
  2. If it matches, you can then keep that tuple, and use ' '.join([i,j]) to join them into 1 string as you expect.
Answered By: Akshay Sehgal

I hope ths will help you

a = ['bww', 1, 'honda', 2, 'ford', 11, 'tesla', 15, 'nissan', 2]
b = ['ford', 'honda']
ls=[]
for item in b:
    if a.__contains__(item):
        ls.append((item+" "+str(a[a.index(item)+1])))
print(ls)
Answered By: Mohit Kumar

Rather than changing the data to suit the code (which some responders seem to think is appropriate) try this:

GROUP = 3

a = ['bmw', '1', '23', 'honda', '2', '55', 'ford', '11', '88', 'tesla', '15', '1', 'kia', '2', '3']
b = ['ford', 'honda']
c = [f'{a[i]} {a[i+1]}' for i in range(0, len(a)-1, GROUP) if a[i] in b]

print(c)

Output:

['honda 2', 'ford 11']

Note:

The assumption here is that input data are presented in groups of three but only the first two values in each triplet are needed.

If the assumption about grouping is wrong then:

c = [f'{a[i]} {a[i+1]}' for i in range(len(a)-1) if a[i] in b]

…which will be less efficient

Answered By: Fred
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.