这段代码的结果
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'
Run Code Online (Sandbox Code Playgroud)
是:
j被发现
未找到
(4,5)被发现
和这块代码的结果
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'
Run Code Online (Sandbox Code Playgroud)
是:
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
Run Code Online (Sandbox Code Playgroud)
但是在第一个,因为你使用逗号分隔key字符串它不会引起任何错误.
| 归档时间: |
|
| 查看次数: |
57 次 |
| 最近记录: |