使用普通的if else时工作正常
vocab = {"a": "4", "i": "1", "u": "5", "e": "3", "o": "0"}
firstchar_name = input("Your name : ") # give fruit suggestion
fruitfrom_name = input("First Character of your name is {}, write any fruit that started with {} : ".format(firstchar_name[0], firstchar_name[0]))
favorite_number = input("Your favorite one-digit number : ")
date_of_born = input("Input your born date (date-month-year) : ")
to_alay = ""
word = list(fruitfrom_name.lower())
for char in word:
to_alay += char if char not in vocab else to_alay += vocab[char]
print(to_alay)
Run Code Online (Sandbox Code Playgroud)
错误:
$ python3 telemakita_password.py
File "telemakita_password.py", line 12
to_alay += char if char not in vocab else to_alay += vocab[char]
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
我想知道为什么+=
在工作但不在+=
其他地方
因为这不是 if-then-else语句.它是三元运算符表达式(或条件表达式),这是一个表达式.这是表达部分:
char if char not in vocab else vocab[char]
Run Code Online (Sandbox Code Playgroud)
var += ...
是不是一种表达,它是语句.这不是问题,我们可以写:
to_alay += char if char not in vocab else vocab[char]
Run Code Online (Sandbox Code Playgroud)
Python将此解释为:
to_alay += (char if char not in vocab else vocab[char])
Run Code Online (Sandbox Code Playgroud)
所以这基本上做你想要的.
dict.get(..)
话虽如此,我认为通过使用.get(..)
,你可以让生活更轻松:
for char in word:
to_alay += vocab.get(char, char)
Run Code Online (Sandbox Code Playgroud)
这更像是"自我解释",每次迭代都是为了获得char
与vocab
dict 中对应的值,如果找不到该键,则回退到char
.
我们甚至可以''.join(..)
在这里使用:
to_alay = ''.join(vocab.get(char, char) for char in word)
Run Code Online (Sandbox Code Playgroud)