python - 了解循环的字符串和列表比较

标签 python python-3.x

我试图理解为什么我编写的这段代码总是显示 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/

相关文章:

python - 升级到 Django 1.7。 AssertionError : To use StatusField, 模型 'ShellRequest' 必须具有 STATUS 选择类属性

python - 在 python 中与应用程序的 UI 交互

python - Tensorflow 2.0 将keras模型转换为.pb文件

python - 在 Python3 中使用 %x 格式化不好吗?

python - 使用 python 3.5 在 centos 6.5 上安装 tkinter

python - 在 OpenERP-7 中通过按钮调用 TreeView

python - 获取在namedtuple中具有最小值的python字典项

python - 从 Python 脚本停止 Mongod 服务器

python - 如何在 numpy Python 中查找一维二进制数组的十进制值

python - 使用pyenv在Python的两个系统版本之间切换