python - 当列表中的元组没有返回任何内容时写入错误
问题描述
tup_list = [(111, 'red'), (222, 'blue'), (333, 'green'), (444, 'red')]
x = input(str("colour? "))
for c in tup_list:
if x in c:
print(c[0])
else:
print("error ")
代码示例^
如果用户输入“red”,则输出为:
111
error
error
444
如果用户输入“蓝色”,则输出为:
error
222
error
error
等等。如果用户输入不在 tup_list 中的“randomchars”(任何随机字符),则输出为:
error
error
error
error
我知道我的代码正在为 tup_list 中的每个 c 打印“错误”。如果用户输入不在 tup_list 中,我希望我的代码一次写入“错误”。我也不明白为什么会为 tup_list 中的每个负匹配打印错误(例如,输入红色正确得到 111 和 444,但它也为蓝色和黄色元组提供了两个错误)。
解决方案
代码正在'error'
为每个c
in打印tup_list
它不匹配,因为您正在迭代每个c
in tup_list
。在每次迭代中,您正在检查颜色是否匹配,并且在每次迭代中您打印它是否匹配(代码编号)或不匹配('error'
)。你可以有一个布尔变量来验证它是否匹配:
tup_list = [(111, 'red'), (222, 'blue'), (333, 'green'), (444, 'red')]
x = input('colour? ')
match = False
for c in tup_list:
if x in c:
print(c[0])
match = True
if not match:
print('error')
推荐阅读
- html - 尝试单击“赞”按钮时出现错误 此页面无法正常工作 HTTP 错误 405
- python - dynamodb 条件更新项(客户端)
- java - 使用java 8将for循环转换为流
- android - 尝试在空对象引用上调用虚拟方法 'android.os.Handler android.app.FragmentHostCallback.getHandler()'
- java - 如果您不知道某些元素是否存在,什么是好的 Selenium 策略?
- javascript - 数组是在函数中定义的,但是当返回它时,它会打印出 undefined
- html - 如何在 spring 控制器部分更改 modelandview 的视图内容?
- python - Gunicorn 粘贴选项
- swift - 如何快速识别连接的网络是开放的还是安全的?
- python - 将图像从图像字段获取到 views.py 模型