python - 协助车工查询

标签 python python-3.x

我有一个有效的条件,但是当我尝试将它压缩到旋工时,我遇到了错误,而且我一生都看不到在哪里。

这是运行的函数:

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]) 。你完全没有必要调用它。

注意:您正在隐藏一些内置名称,例如 dictinput。不要这样做,因为随着代码库的增长,您可能会遇到(时髦的)错误。

您的未压缩形式可以工作,但不是因为您的想法。调用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())

关于python - 协助车工查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57968565/

相关文章:

Python itertools.combinations : how to obtain the indices of the combined numbers

python - 是否可以在 python 中使用 NetworkX 控制节点绘制的顺序?

python - 使用 python 生成一个二进制缓冲区,以在 C 中作为结构读取

python - 如何在 pyglet 中制作 3D?

python - python 中将此列表更改为另一个列表的功能方法

python - 不能定义 2 是否为质数

python - 在 cython 中返回 c++ std::array<std::string, 4> 的包装方法

python - python 3 中的 List 中的特定模式字符串

python - PEP 479、map() 和 StopIteration

Python 缩进错误 : unindent does not match any outer indentation level