python - 如何使用循环列表的 if 语句调用函数?Python
问题描述
在这里编程是全新的,并且在家庭作业问题上遇到了很多麻烦。请原谅我缺乏理解和知识。任何帮助将不胜感激!谢谢!!当我正在调用的项目之一不在列表中时,我正在尝试输出一个 if 语句,并且该函数应该打印出该项目。
def sushi(order):
toppings = ['salmon', 'tuna', 'whitefish']
for item in toppings:
if 'salmon' or 'tuna' or 'whitefish' in toppings:
print('all set')
break
if not item in toppings:
print('Add to this', toppings.append(order))
print('all set')
sushi(['salmon', 'tuna'])
sushi(['salmon', 'tuna', 'tempura'])
我希望它输出:
all set
Add to this tempura
all set
解决方案
我相信您正在寻找的是:
def sushi(order):
toppings = ['salmon', 'tuna', 'whitefish']
for item in order:
if item not in toppings:
print('Add to this', item)
print("All set!")
>>> sushi(['salmon', 'tuna'])
All set!
>>> sushi(['salmon', 'tuna', 'tempura'])
Add to this tempura
All set!
可以通过将其更改为来缩短循环:
for item in [x for x in order if x not in toppings]:
print('Add to this', item)
你的问题是:
1)for item in toppings:
我猜你想要这里order
而不是toppings
2)if 'salmon' or 'tuna' or 'whitefish' in toppings:
在这里,您可能希望它是:if 'salmon' in toppings or 'tuna' in toppings or 'whitefish' in toppings:
. 你写的是“如果字符串'salmon'存在或字符串'tuna'存在或字符串'whitefish'在浇头中”。
3)print('Add to this', toppings.append(order))
该方法append
不返回任何内容。也许你想要的是添加一行说toppings.append(item)
然后简单地打印item
推荐阅读
- android - 颤振和火力过滤器
- apache-spark - 加速实验,将Spark限制为单核
- node.js - 在 Angular 和 nodejs 中上传图像时,表单数据不保存
- jwt - 为什么使用 JWT 刷新令牌
- azure - Azure 函数应用在首次部署时间歇性失败:“资源应在部署之前存在。”
- google-cloud-firestore - 特定子集合的云消息传递
- laravel - Laravel Livewire 数据在渲染后转换为数组
- javascript - 即使对于反应中的状态 200,API 也没有获取任何响应(Fetch API)
- javascript - 为什么 getExpectedRate() 返回 0?
- ios - 在 Xcode 13 UIButton setBackgroundImage 中不起作用