python - 列表理解追加到新列表
问题描述
我正在尝试遍历列表“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']
我可以看到它正在为食物中的每个元素附加匹配项,但我不确定如何进行列表理解以获得我想要的输出。
任何帮助,将不胜感激!感谢大家!
解决方案
尝试这个:
order = [x for x in menu for y in food if( y in x)]
推荐阅读
- azure-devops - 添加文件以构建包工件
- ios - TestFlight 的公共链接的兑换码在哪里?
- bash - Fiddler 不显示来自 git bash 客户端的 HTTPS 流量
- django - Django - 导入 .txt 文件以填充数据
- node.js - 网络在长时间循环中冻结
- sql - 如何在 SQL 中过滤每个 id 只有一个初始行的行?
- c# - 使用 vars 为每个用户设置 Visual Studio 2017 的输出构建路径
- ios - IOS App Store Connect 未显示新的构建状态
- javascript - 如何修改此 HTML 文档以使用 DOM 2 事件模型
- java - simpledateformat (android) 2018-10-03T09:00:36.845+0000 的日期格式是什么?