首页 > 解决方案 > 当列表中的元组没有返回任何内容时写入错误

问题描述

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,但它也为蓝色和黄色元组提供了两个错误)。

标签: pythonlistfor-looptuplesnested-lists

解决方案


代码正在'error'为每个cin打印tup_list它不匹配,因为您正在迭代每个cin 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')

推荐阅读