为什么 list.append() 返回 None?[重复]
- 2025-03-04 08:24:00
- admin 原创
- 82
问题描述:
我正在尝试使用 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)
解决方案 1:
只需替换a_list = a_list.append(r)
为a_list.append(r)
。
大多数改变序列/映射项的函数、方法都会返回None
:list.sort
,,...list.append
`dict.clear`
没有直接关系,但请参阅为什么 list.sort() 不返回排序后的列表?。
解决方案 2:
该方法append
不返回任何内容:
>>> l=[]
>>> print l.append(2)
None
你不能写:
l = l.append(2)
但简单来说:
l.append(2)
在您的示例中,替换:
a_list = a_list.append(r)
到
a_list.append(r)
解决方案 3:
对于附加的返回数据使用:
b = []
a = b.__add__(['your_data_here'])
解决方案 4:
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)
到
a_list.append(r)
解决方案 5:
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]
就是这样。所以,希望它能帮助你。
解决方案 6:
列表方法可以分为两种类型:一种是就地改变列表并返回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)
解决方案 7:
只是一个想法,那些函数(操纵实际数据)不应该返回 None,而应该什么都不返回。这样用户至少会发现问题,因为它会抛出一个错误,指出一些赋值错误!!评论你的想法!!
解决方案 8:
以防万一有人在这里结束,我在尝试附加回拨时遇到了这种行为
这按预期工作
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")
扫码咨询,免费领取项目管理大礼包!