列表理解附加到新列表

List comprehension to append to new list

我正在尝试遍历列表“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']

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

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

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

如有任何帮助,我们将不胜感激!谢谢大家!

试试这个:

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

您可以在 set 的帮助下完成此操作,因此您只需要一个 for 循环

order = [item for item in menu if len(set(item.split()) & set(food)) > 0]

有了这个我得到了相同的输出

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

输出: ['warm apple pie', 'chicken pot pie']

您也可以检查 here 以获取更多示例。

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]

我试过并得到正确的输出如下:

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