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

13
我正在尝试使用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)

3
完全与您的问题无关,但是 1/ 您可能想阅读 operator 模块的文档,2/ 在您的 calc 函数中,您根本不需要使用 lambda - 只需映射到操作符函数并在调用时传递参数,即:{"+": add, "-":sub,}[opt](x, y)。这也允许您全局定义映射,因此避免在每次调用 calc 时重复构建它。 - bruno desthuilliers
@brunodesthuilliers,谢谢,太棒了!!! - newlife
8个回答

21

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

大多数 改变序列/映射项目的函数和方法确实会返回 None: list.sort, list.append, dict.clear ...

虽与此内容不直接相关,但请参见为什么list.sort()不返回已排序的列表?


我不同意 sorted。它返回排序后的列表。 - Maxime Chéramy
1
你提供的关于 list.sort() 方法的常见问题解答链接非常相关。我们可以很容易地理解为什么 append 不会返回一个新列表,而是直接修改参数。(+1) - Maxime Chéramy

17

方法append不返回任何内容:

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

你不应该写:

l = l.append(2)

但简单来说:

l.append(2)

在你的例子中,将以下内容替换:

a_list = a_list.append(r)

a_list.append(r)

非常感谢您的快速回答和相关讨论。只有一个绿色的 V 可以点击... - newlife

6

要获取添加后的返回数据,请使用以下方法:

b = []   
a = b.__add__(['your_data_here'])

很好 - 我只需在我的代码中将.append替换为.__add__。这些list方法不能链式调用真是让人头疼。那么,.extend的类比等效方法是什么? - WestCoastProjects

1

append函数改变了列表并返回None。下面是执行这个操作的代码http://hg.python.org/cpython/file/aa3a7d5e0478/Objects/listobject.c#l791

listappend(PyListObject *self, PyObject *v)
{
    if (app1(self, v) == 0)
        Py_RETURN_NONE;
    return NULL;
}

所以,当你说

a_list = a_list.append(r)

你实际上是将a_list赋值为None。因此,下一次引用a_list时,它不再指向列表而是None。所以,正如其他人建议的那样,改变。
a_list = a_list.append(r)

to

a_list.append(r)

0

列表方法可以分为两类:一类是在原地修改列表并返回None(字面上)的方法,另一类是保持列表不变并返回与列表相关的某个值的方法。

第一类:

append
extend
insert
remove
sort
reverse

第二类:

count
index

以下示例解释了它们之间的区别。
lstb=list('Albert')
lstc=list('Einstein')

lstd=lstb+lstc
lstb.extend(lstc)
# Now lstd and lstb are same
print(lstd)
print(lstb)

lstd.insert(6,'|')
# These list-methods modify the lists in place. But the returned
# value is None if successful except for methods like count, pop.
print(lstd)
lstd.remove('|')
print(lstd)

# The following return the None value
lstf=lstd.insert(6,'|')
# Here lstf is not a list.
# Such assignment is incorrect in practice.
# Instead use lstd itself which is what you want.
print(lstf)

lstb.reverse()
print(lstb)

lstb.sort()
print(lstb)

c=lstb.count('n')
print(c)

i=lstb.index('r')
print(i)

pop方法两者兼备。它既改变列表,又返回一个值。

popped_up=lstc.pop()
print(popped_up)
print(lstc)

0

以防有人到这里,我在尝试追加返回调用时遇到了这种行为

这运作得很好

def fun():
  li = list(np.random.randint(0,101,4))
  li.append("string")
  return li

这会返回 None

def fun():
  li = list(np.random.randint(0,101,4))
  return li.append("string")

0

像list.append()、list.sort()这样的函数不会返回任何东西。

def list_append(p):
    p+=[4]

函数list_append没有返回语句。因此,当您运行以下语句时:

a=[1,2,3]
a=list_append(a)
print a
>>>None

但是当您运行以下语句时:

a=[1,2,3]
list_append(a)
print a
>>>[1,2,3,4]

就是这样。希望能对你有所帮助。


0

仅是一种想法,与其让那些操作实际数据的函数返回None,它们应该返回空值。 这样至少用户会捕捉到问题,因为它会抛出一个指示某个赋值错误的错误! 请留下您的想法!


在Python中,“返回空值”意味着返回None - Dmitry Kuzminov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接