目前我有一个字母表中特定字母的替换列表。字母a
将替换为第一索引中的任何值,b
以及 second 索引处的任何值,依此类推。
我在Python中欣赏的一个功能是能够执行列表推导。但是,当我试图连接时,我没有得到积极的结果。
letters = ["ka","zu","mi","te","ku","lu","ji","ri","ki","zu","me","ta","rin","to","mo",
"no","ke","shi","ari","chi","do","ru","mei","na","fu","zi"]
def nameToNinja(str):
name = ""
for i in str:
i=i.lower()
if ord(i) >= 97 and ord(i) <= 122:
name+= letters[ord(i.lower()) - 97]
else:
name += i
return name
name = "Obama"
print("Your ninja name is: {0}".format(nameToNinja(name)))
我尝试将函数转换为Python中的列表解析不起作用。事实上,我收到的唯一错误是Syntax Error
。
尝试:
def nameToNinja(str):
return ''.join([letters[ord(i.lower()) - 97] if ord(i.lower()) >= 97 and ord(i.lower()) <= 122 else i
for i in str)
将原始函数缩短为连续列表解析的正确方法是什么。
答案 0 :(得分:2)
letters = ["ka","zu","mi","te","ku","lu","ji","ri","ki","zu","me","ta","rin","to","mo","no","ke","shi","ari","chi","do","ru","mei","na","fu","zi"]
def nameToNinja(str):
return ''.join([letters[ord(i.lower()) - 97] if (97 <= ord(i.lower()) <= 122) else i.lower() for i in str])
name = "Obama"
print("Your ninja name is: {0}".format(nameToNinja(name)))
答案 1 :(得分:2)
每个字母只调用一次.lower()
:
def name_to_ninja(s):
return ''.join(letters[ord(x) - 97] if ord(x) >= 97 and ord(x) <= 122 else x
for x in (y.lower() for y in s))
name = "Obama"
print("Your ninja name is: {0}".format(name_to_ninja(name)))
输出:
Your ninja name is: mozukarinka
答案 2 :(得分:-1)
letters = ["ka","zu","mi","te","ku","lu","ji","ri","ki","zu","me","ta","rin","to","mo","no","ke","shi","ari","chi","do","ru","mei","na","fu","zi"]
name = "Obama"
ninja_name = ''.join(
[letters[ord(i)-ord('a')] if i.islower() else i for i in name]
)
print("Name:", name, "Ninjaname:", ninja_name)