简体   繁体   中英

List comprehension to append to new list

I am trying to iterate through each element in list "food", and if that element is in list "menu", I want to append that element to a new list "order". I have been able to do this with the for loop below:

food = ['apple', 'donut', 'carrot', 'chicken']
menu = ['chicken pot pie', 'warm apple pie', 'Mac n cheese']
order = []

for i in food:
    for x in menu:
        if i in x:
            order.append(x)

# Which gives me

order = ['warm apple pie', 'chicken pot pie']

I know this works, and this is what I want, but I am trying to improve my code to make it more pythonic. I have tried this:

order = [x for x in menu for y in food]

But that gives me:

order = ['chicken pot pie', 'chicken pot pie', 'chicken pot pie', 'chicken pot pie',
         'warm apple pie', 'warm apple pie', 'warm apple pie', 'warm apple pie', 
         'Mac n cheese', 'Mac n cheese', 'Mac n cheese','Mac n cheese']

I can see that it is appending matches for each element in food, but I'm not sure how to do list comprehension to get my desired output.

Any help would be appreciated! Thanks everyone!

Try this:

order = [x for x in menu for y in food if( y in x)]

With this I get the same output

order = [x for i in food for x in menu if i in x]

Output: ['warm apple pie', 'chicken pot pie']

Also you could check here for mor examples.

You can do this with the help of set , therefore you need only one for loop

order = [item for item in menu if len(set(item.split()) & set(food)) > 0]
order = list(filter((None).__ne__, [x if y in x else None for x in menu for y in food]))
order = [menu_item for menu_item in menu for food_item in food if food_item in menu_item]

I tried and got correct output as below:

>>> order = [menu_item for menu_item in menu for food_item in food if food_item in menu_item]
>>> order
['chicken pot pie', 'warm apple pie']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM