与“不同的结果”;在;运算符,Python
这段代码的结果与“不同的结果”;在;运算符,Python,python,Python,这段代码的结果 items = ['j','ak',(4,5)] tests = ['j','as',(4,5)] for key in tests: for item in items: if item==key: print key,'was found' break else: print key,'not found' items = ['j','ak',(4,5)] tests = ['j
items = ['j','ak',(4,5)]
tests = ['j','as',(4,5)]
for key in tests:
for item in items:
if item==key:
print key,'was found'
break
else:
print key,'not found'
items = ['j','ak',(4,5)]
tests = ['j','as',(4,5)]
for key in tests:
if key in items:
print key+' was found'
else:
print key+' not found'
是:发现j
因为找不到
(4,5)被发现
以及这段代码的结果
items = ['j','ak',(4,5)]
tests = ['j','as',(4,5)]
for key in tests:
for item in items:
if item==key:
print key,'was found'
break
else:
print key,'not found'
items = ['j','ak',(4,5)]
tests = ['j','as',(4,5)]
for key in tests:
if key in items:
print key+' was found'
else:
print key+' not found'
是:发现j
因为找不到
现在,问题是:为什么第二个块中的(4,5)在“测试”和“项目”中不进行比较,而两个块的结果应该是相同的?这是否与“in”运算符有关?您的第二个代码将为最后一个元组项引发
TypeError
,因为您正在用字符串连接键:
>>> items = ['j','ak',(4,5)]
>>> tests = ['j','as',(4,5)]
>>> for key in tests:
... if key in items:
... print key+' was found'
... else:
... print key+' not found'
...
j was found
as not found
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
TypeError: can only concatenate tuple (not "str") to tuple
>items=['j','ak',(4,5)]
>>>测试=['j','as',(4,5)]
>>>对于钥匙插入测试:
... 如果输入项目:
... 打印键+'已找到'
... 其他:
... 打印键+“未找到”
...
j被发现
未找到
回溯(最近一次呼叫最后一次):
文件“”,第3行,在
TypeError:只能将元组(而不是“str”)连接到元组
但在第一个示例中,由于您使用逗号将
键与字符串分隔,因此不会产生任何错误。我认为是因为最后一个示例在打印中有错误
尝试: