Home > Back-end >  Get new list from substrings between two lists with list comprehension
Get new list from substrings between two lists with list comprehension

Time:09-08

Having the following 2 lists

a =["my car","your car","his car","her car","their car","her bike","your house","his job"]
b = ["your","her"]

I'm trying to get the elements from list a that contains the string of elements in list b in the same order of appeareance, so the expected output would be like

out = ["your car","her car","her bike","your house"]

My attempt with nested for loop that works is this

out = []
for z in a:
    for w in b:
        if w in z:
            out.append(z)

I'm stuck in trying to convert to list comprehension. I've tried suggestions from this question in the way below but I'm getting wrong answer. Thanks for any help

>>> [[z for z in a] for w in z if w in z]
[['my car', 'your car', 'his car', 'her car', 'their car', 'her bike', 'your house', 'his job'], 
 ['my car', 'your car', 'his car', 'her car', 'their car', 'her bike', 'your house', 'his job'], 
 ['my car', 'your car', 'his car', 'her car', 'their car', 'her bike', 'your house', 'his job'], 
 ['my car', 'your car', 'his car', 'her car', 'their car', 'her bike', 'your house', 'his job'], 
 ['my car', 'your car', 'his car', 'her car', 'their car', 'her bike', 'your house', 'his job'], 
 ['my car', 'your car', 'his car', 'her car', 'their car', 'her bike', 'your house', 'his job'], 
 ['my car', 'your car', 'his car', 'her car', 'their car', 'her bike', 'your house', 'his job']]
>>>

CodePudding user response:

[ELEMENT for x in a for y in b if y in x]

ELEMENT: whatever expression you define which is generated for every iteration to its right, if the trailing condition is satisfied

>>> a =["my car","your car","his car","her car","their car","her bike","your house","his job"]
>>> b = ["your","her"]
>>> [x for x in a for y in b if y in x]
['your car', 'her car', 'her bike', 'your house']

CodePudding user response:

Given the solution you say that DOES work:

out = []
for z in a:
    for w in b:
        if w in z:
            out.append(z)

Converting this to list comprehension is basically just like reading down the stack

out = [z for z in a for w in b if w in z]
  • Related