【问题标题】:Insert at first position of a list in Python [closed]在Python中插入列表的第一个位置[关闭]
【发布时间】:2014-03-23 06:37:13
【问题描述】:

如何在列表的第一个索引处插入元素? 如果我使用list.insert(0, elem)elem 会修改第一个索引的内容吗? 还是我必须用第一个元素创建一个新列表,然后将旧列表复制到这个新列表中?

【问题讨论】:

标签: python list insert


【解决方案1】:

使用insert:

In [1]: ls = [1,2,3]

In [2]: ls.insert(0, "new")

In [3]: ls
Out[3]: ['new', 1, 2, 3]

【讨论】:

    【解决方案2】:

    来自文档:

    list.insert(i, x)
    在给定位置插入一个项目。首先 参数是要插入的元素的索引,所以 a.insert(0, x) 插入到列表的前面,a.insert(len(a),x) 是 相当于a.append(x)

    http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-15
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多