我正在学习Python并且对if not
在下面的代码中做了什么感到困惑?我认为if not
就像else
一样。但事实证明我错了。此代码中if not exists
的值是多少?还有一个天真的问题,变量exists
是在for循环中定义的,为什么它在全局范围内可用?
import scrabble
import string
for letter in string.ascii_lowercase:
for word in scrabble.wordlist:
exists = False
if letter * 2 in word:
exists = True
break
if not exists:
print(letter)
print(exists) # Globally exists = True
答案 0 :(得分:1)
以下是一些解释:
import string
# let's create our own wordlist
wordlist = ["cat","moose"]
# Loop all letters from a-z
for letter in string.ascii_lowercase:
# Inner-loop all words in wordlist
for word in wordlist:
# Start with exists = False
exists = False
# If letter is repeated break the inner loop and set exists = True
if letter * 2 in word:
exists = True
break
# Check if exists is False (which it is if double letter didn't exist in any word)
if not exists:
print(letter)
# This will print the last exists value (True if 'z' is doubled in any word else false)
print(exists)
由于在wordlist中的任何一个单词中重复的唯一字母是' o'所有字母除了' o'打印出来后跟一个假的
a
b
c
d
...
False
顺便说一句,您可以使用此代码段获得相同的结果:
import string
doubleletters = []
wordlist = ["cat","moose"]
# Loop through wordlist and extend the doubleletters list
for word in wordlist:
doubleletters.extend(i[0] for i in zip(word,word[1:]) if len(set(i)) == 1)
print('\n'.join(i for i in string.ascii_lowercase if i not in doubleletters))
答案 1 :(得分:0)
在python中不会翻转布尔值(true或false)的值。 if not x
可以读为"如果x为false",那么如果exists
等于False
,if块中的语句将会执行,即如果没有已找到重复的字母。