【问题标题】:Why does list.append() return None? [duplicate]为什么 list.append() 返回 None? [复制]
【发布时间】:2013-11-16 09:22:57
【问题描述】:

我正在尝试使用 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/ 您可能需要阅读 operator 模块的文档,以及 2/ 在您的 calc 函数中您根本不需要 lambda - 只需映射到运算符函数并在调用时传递参数,即:{"+": add, "-":sub,}[opt](x, y)。这也将允许您在全局范围内定义映射,从而避免在每次调用 calc 时一次又一次地构建它。
  • @brunodesthuilliers,谢谢,太好了!!!

标签: python


【解决方案1】:

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,,,
【解决方案2】:

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

大多数函数、改变序列/映射项的方法确实返回Nonelist.sortlist.appenddict.clear ...

没有直接关系,但见Why doesn’t list.sort() return the sorted list?

【讨论】:

  • 我不同意sorted。它返回排序列表。
  • 您指向有关list.sort() 方法的常见问题解答的链接非常相​​关。我们很容易理解为什么 append 不返回新列表而是直接修改参数。 (+1)
【解决方案3】:

对于附加使用的返回数据:

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

【讨论】:

  • 这很好 - 我只是在我的代码中将 .append 替换为 .__add__`。这些 list 方法不可链接,这是一个 PITA。 .extend 的类似等价物是什么?
【解决方案4】:

只是一个想法,而不是那些函数(操纵实际数据)返回 None,它们应该什么都不返回。 然后至少用户会发现这个问题,因为它会抛出一个错误,说明一些分配错误! 评论你的想法!!

【讨论】:

  • 在 Python 中“不返回任何内容”意味着返回 None
【解决方案5】:

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)

您实际上是用None 分配a_list。因此,下次当您引用a_list 时,它不是指向列表而是指向None。所以,正如其他人所建议的,改变

a_list = a_list.append(r)

a_list.append(r)

【讨论】:

    【解决方案6】:

    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]
    

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

    【讨论】:

      【解决方案7】:

      列表方法可以分为两种类型,一种是改变列表并返回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)
      

      【讨论】:

        【解决方案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")
        

        【讨论】:

          猜你喜欢
          • 2018-11-29
          • 2016-10-04
          • 2013-08-14
          • 2012-05-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-11
          相关资源
          最近更新 更多