为什么 list.append() 返回 None?

新手上路,请多包涵

我正在尝试使用 Python 计算后缀表达式,但没有成功。我认为这可能是与 Python 相关的问题。

有什么建议么?

 expression = [12, 23, 3, '*', '+', 4, '-', 86, 2, '/', '+']

def add(a,b):
    return a + b
def multi(a,b):
    return a* b
def sub(a,b):
    return a - b
def div(a,b):
    return a/ b

def calc(opt,x,y):
    calculation  = {'+':lambda:add(x,y),
                     '*':lambda:multi(x,y),
                     '-':lambda:sub(x,y),
                     '/':lambda:div(x,y)}
    return calculation[opt]()

def eval_postfix(expression):
    a_list = []
    for one in expression:
        if type(one)==int:
            a_list.append(one)
        else:
            y=a_list.pop()
            x= a_list.pop()
            r = calc(one,x,y)
            a_list = a_list.append(r)
    return content

print eval_postfix(expression)

原文由 newlife 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 736
2 个回答

只需将 a_list = a_list.append(r) 替换为 a_list.append(r)

Most functions, methods that change the items of sequence/mapping does return None : list.sort , list.append , dict.clear

没有直接关系,但请参阅 为什么 list.sort() 不返回排序列表? .

原文由 falsetru 发布,翻译遵循 CC BY-SA 3.0 许可协议

该方法 append 不返回任何内容:

 >>> l=[]
>>> print l.append(2)
None

你不能写:

 l = l.append(2)

但简单地说:

 l.append(2)

在您的示例中,替换:

 a_list = a_list.append(r)

a_list.append(r)

原文由 Maxime Chéramy 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题