当我使用输入" abc"运行它时,它只打印" f"而不是" def"我无法弄清楚为什么......帮助
code = raw_input("Enter your code: ")
translation = {"a": "d", "b": "e", "c": "f", "d": "g", "e": "h", "f": "i", "g": "j", "h": "k", "i": "l", "j": "m", "k": "n", "l": "o", "m": "p", "n": "q", "o": "r", "p": "s", "q": "t", "r": "u", "s": "v", "t": "w", "u": "x", "v": "y", "w": "z", "x": "a", "y": "b", "z": "c"}
lettered_code = list(code)
def translate(lettered_code):
for letters in lettered_code:
newanswer = translation[letters]
return newanswer
print translate(lettered_code)
答案 0 :(得分:0)
您只返回最后一次翻译,每次迭代都会newanswer = translation[letters]
,因此您只能看到最后一次。
将每个新char添加到字符串中:
def translate(lettered_code):
new_answer = "" # set variable outside the for loop to an empty string
for letters in lettered_code:
new_answer += translation[letters] # add each translated letter to new_answer
return new_answer # return all joined letters
您不需要lettered_code = list(code)
,您可以直接迭代字符串,只需将code
传递到您的函数中。
您还可以使用join和list comprehension创建已翻译的字符列表,并将它们连接成一个字符串:
def translate(lettered_code):
"".join([translation[letters] for letters in lettered_code ])
答案 1 :(得分:-1)
你要早点回来,你想要
def translate(lettered_code):
return [translation[letter] for letter in lettered_code]