我试图理解为什么我编写的这段代码总是显示 true,即使它应该显示 false?
word = "the sky is blue"
checkList = ["a", "e", "i", "o", "u"]
for i in word.lower():
if (i != checkList[0]) or (i != checkList[1]) or (i != checkList[2]) or (i != checkList[3]) or (i != checkList[4]):
print("true")
else:
continue
最佳答案
使用 and
而不是 or
可以,但更好的是:
for i in word.lower():
if i not in checkList:
print("true")
else:
continue
或者最好的是:
print('\n'.join(['true' for i in word.lower() if i not in checkList]))
或者如果 python3 (注意:有点低效,因为我使用列表理解作为副作用。 ):
print(*['true' for i in word.lower() if i not in checkList],sep='\n')
但如果是 python 2,则将 from __future__ import print_function
或者最短的:
[print('true') for i in word.lower() if i not in checkList]
请注意,所有示例中的 checkList
可以是:
'aeiou'
关于python - 了解循环的字符串和列表比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53037945/