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
CodePudding user response:
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:
- 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.
- Next you can compare the first item
i[k]
in each tuple(i[k],i[k 1])
with elements from listb
, usingif i in b
- If it matches, you can then keep that tuple, and use
' '.join([i,j])
to join them into 1 string as you expect.
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
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)