首页 > 解决方案 > 列表理解追加到新列表

问题描述

我正在尝试遍历列表“food”中的每个元素,如果该元素在列表“menu”中,我想将该元素附加到新列表“order”中。我已经能够使用下面的 for 循环来做到这一点:

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']

我知道这行得通,这就是我想要的,但我正在努力改进我的代码以使其更 Pythonic。我试过这个:

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

但这给了我:

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']

我可以看到它正在为食物中的每个元素附加匹配项,但我不确定如何进行列表理解以获得我想要的输出。

任何帮助,将不胜感激!感谢大家!

标签: pythonlist-comprehension

解决方案


尝试这个:

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

推荐阅读