【问题标题】:Why do we get a 'None' item when appending an item to an existing list? [duplicate]为什么在将项目附加到现有列表时会得到“无”项目? [复制]
【发布时间】:2019-05-04 17:13:44
【问题描述】:

用例:
我想将一个新项目与列表中的所有现有项目一起附加到同一个列表中。
例如:

list = [ 'a', 'b', 'c']

附加'd',期望输出为:['a', 'b', 'c', 'a', 'b', 'c', 'd']

我的代码:

list.append(list.append('d'))

当前输出:

['a', 'b', 'c', 'd', None]

为什么我会在此处收到 None 项目,如何按预期打印列表?

【问题讨论】:

  • 注意:应该避免隐藏像list 这样的内置名称。我建议使用不同的变量名。

标签: python list


【解决方案1】:

请改用list.append('d')

list 中的append 函数不返回任何内容,因此将添加list.append(list.append('d')) None

要打印预期的列表(让列表为 'l'):

list_old = list(l)
l += l # ['a', 'b', 'c'] -> ['a', 'b', 'c', 'a', 'b', 'c']
l.append('d')
list_old.extend(l)

【讨论】:

    【解决方案2】:

    list.append 返回None。这是因为list.append 是一个就地 操作。此外,您正在对内置进行遮蔽,不建议这样做。

    可以 append 复制一份,然后extend 您的原始列表:

    L = ['a', 'b', 'c']
    L_to_append = L.copy()
    L_to_append.append('d')
    L.extend(L_to_append)
    

    但这很冗长。您可以只使用+= 运算符:

    L = ['a', 'b', 'c']
    L += L + ['d']
    
    print(L)
    
    ['a', 'b', 'c', 'a', 'b', 'c', 'd']
    

    【讨论】:

      猜你喜欢
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-15
      • 2020-05-29
      • 2015-04-16
      • 1970-01-01
      • 2012-11-10
      • 2020-09-20
      相关资源
      最近更新 更多