python - 车工查询协助
问题描述
我有一个可行的条件,但是当我尝试将其压缩到车削时,我得到了错误,并且我一生都看不到在哪里。
这是运行的函数:
def alphabet_position(text):
output = ""
dict = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8','i':'9','j':'10','k':'11','l':'12','m':'13','n':'14','o':'15','p':'16','q':'17','r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25','z':'26'}
input = list(text.lower())
for i in input:
if i not in dict:
next
else:
output += (dict[i]+" ")
return output.rstrip()
这就是我要压缩的内容:
for i in input:
output += (dict[i]+" ") if i in dict else next
但它不会运行,我得到这个错误作为输出:
Traceback (most recent call last):
File "main.py", line 4, in <module>
test.assert_equals(alphabet_position("The sunset sets at twelve o' clock."), "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11")
File "/home/codewarrior/solution.py", line 6, in alphabet_position
output += (dict[i]+" ") if i in dict else next
TypeError: must be str, not builtin_function_or_method
解决方案
检查[Python 3.Docs]: Built-in functions - next ( iterator[, default] )。你完全没有必要调用它。
注意:您正在隐藏一些内置名称,例如dict、input。不要这样做,因为随着代码库的增长,您可能会遇到(时髦的)错误。
您未压缩的表格有效,但不是因为您的想法。调用next是多余且无用的。您的循环相当于:
for i in input_list:
if i in dictionary:
output += (dictionary[i] + " ")
至于压缩形式,您的意思是:
output += (dictionary[i] + " ") if i in dictionary else "" # NOT next
但你可以做得更好:具有列表理解的单行,由字符串包裹:
output = " ".join([dictionary[i] for i in input_list if i in dictionary])
从那里开始,整个函数可能看起来像(通过摆脱辅助字典,并使用(小写字母)字符ASCII代码的属性):
def alphabet_position(text):
return " ".join(str(ord(c) - 0x60) for c in text.lower() if c.islower())