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

Python 了解循环的字符串和列表比较,python,python-3.x,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]): pr

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

没有一个字符串可能同时等于所有这些不同的字母,因此它必然总是不等于它们中的大多数。您的ors应该是解决问题的工具,因为您关心的是它不等于它们中的任何一个,而不是它不等于它们的所有。

使用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注:有点低效,因为我使用列表理解作为副作用。 :

但如果是python 2,则从_ufuture _;导入print_函数

或最短的:

[print('true') for i in word.lower() if i not in checkList]
注:在所有示例中,检查表可以是:

在节中

if (i != checkList[0])
天空中包含的每个i都是蓝色的,不同于a,因此您的条件在Python中每次都是真的,或者条件以一种特定的方式工作,即如果第一个条件为真,它将不检查其他条件,但如果条件为假,它将检查所有其他条件,除非它找到了真的条件。在您的情况下,您可以这样做:

word = "the sky is blue"
checkList = ["a", "e", "i", "o", "u"]

for i in word.lower():
    if i in checkList:
         print("true")
    else:
        continue
您需要使用and而不是or,除此之外,还有更好的字符计数方法。例如,你可以使用地图


我要去睡一觉,所以我自己不会去尝试,但我想你也可以在这里好好利用。@usr2564301 hmmm。。。怎么做?是不是[在word中为i打印'true'。如果我不在检查表中,请降低]会产生副作用的不良做法?谢谢你的解释-有什么地方我可以更好地理解这些操作吗?有很多关于它的文章。这将对你有帮助。为什么“在chars中”?删除它,这是一个错误@U9 Forward你想做什么?如果您希望在检查表中出现命中时打印true,请使用==not!=。
if (i != checkList[0])
word = "the sky is blue"
checkList = ["a", "e", "i", "o", "u"]

for i in word.lower():
    if i in checkList:
         print("true")
    else:
        continue
word = "the sky is blue"
chars = 'aeiou'

print(*map(lambda x : "{}:{}".format(x, word.lower().count(x)), chars))
# output,
a:0 e:2 i:1 o:0 u:1 
word = "the sky is blue"
checkList = ["a", "e", "i", "o", "u"]
print [x not in checkList for x in word]

Result:[True, True, False, True, True, True, True, True, False, True, True, True, True, False, False]