【问题标题】:How to add a string at the end of a list with python?如何用python在列表末尾添加一个字符串?
【发布时间】:2014-12-11 05:36:26
【问题描述】:

大家好,我是 python 新手,我想在元组列表的第 n 项添加一个新字符串,假设如下:

_list = [('string0', 'string1'),.... ,('stringN', 'stringN-1')]

我想添加另一个这样的字符串:

_list = [('string0', 'string1'),.... ,('stringN', 'stringN-1'),'NEW_STRING']

已编辑:

我用 append 方法尝试了以下方法:

_list.append('NEW_STRING')

print "this is the updated list",_list

知道如何在 n 个元组列表的末尾合并一个新字符串吗?

【问题讨论】:

  • 首先,不要使用list 作为可验证的名称。那么为什么你的例子不起作用,有什么错误吗?
  • 对不起,伙计们现在可以使用了!谢谢。让我在未来为大家更新这个问题的正确答案。

标签: python list python-2.7 tuples nested-lists


【解决方案1】:

试试下面的代码 .append() 应该可以工作。

list = [('string0', 'string1'),('stringN', 'stringN-1')]
list.append("hello")
print list

【讨论】:

    【解决方案2】:

    list.append 可以就地更改您的对象(您不应将其称为 list)。

    list.append('NEW_STRING')
    print list
    

    【讨论】:

    • 当我尝试使用这个和其他答案时,会出现以下异常:TypeError'NoneType' obtect is not iterable
    【解决方案3】:
    >>> my_list = ['a','b']
    >>> print "hello", my_list.append('c')   
    hello None
    >>> my_list
    ['a', 'b', 'c']
    

    你的代码可以工作,字符串会被追加,但是因为追加返回 None,所以它会打印 None

    所以为了避免打印 None,把 append 放在下一行。

    注意:使用列表作为变量名是不好的做法,因为list是python中的内置函数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-10
      相关资源
      最近更新 更多