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

时间:2018-10-29 02:25:08

标签: python python-3.x

我试图理解为什么我编写的这段代码即使显示为假也总是显示为真?

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

6 个答案:

答案 0 :(得分:2)

使用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'

答案 1 :(得分:1)

Python 中,or条件以一种特殊的方式工作,如果第一个条件为true,则不会检查其他条件,但是如果条件为false,它将除非找到条件true,否则请检查所有其他条件。您可以这样做:

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

for i in word.lower():
    if i in checkList:
         print("true")
    else:
        continue

答案 2 :(得分:1)

您需要使用and而不是or,此外,还有更好的计数字符的方法。例如,您可以使用map

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 

答案 3 :(得分:0)

任何字符串都不可能一次等于所有这些不同的字母,因此它必然总是与大多数字母不相等。您的or应该是and,以解决此问题,因为您关心的是它不等于其中的任何,而不是不等于所有< / strong>。

答案 4 :(得分:0)

在该部分

if (i != checkList[0])

“天空中的蓝色”与“ a”不同,因此您的情况每次都是真实的

答案 5 :(得分:0)

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]