问题:在Python列表的第一位置插入[关闭]

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

How can I insert an element at the first index of a list ? If I use list.insert(0,elem), do elem modify the content of the first index? Or do I have to create a new list with the first elem and then copy the old list inside this new one?


回答 0

用途insert

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

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

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

Use insert:

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

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

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

回答 1

从文档中:

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

From the documentation:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

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


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。