python中List操作

传送门 官方文件地址

list.append(x):

       将x加入列表尾部,等价于a[len(a):] = [x]

       例:

>>> list1=[1,2,3,4]
>>> list1.append(5)
>>> list1
[1, 2, 3, 4, 5]

list.extend(L)

将列表L中的元素加入list中,等价于a[len(a):] = L.

例:

>>> list1=[1,2,3,4]
>>> L=[5,6,7,8]
>>> list1.extend(L)
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8]

 

list.insert(i, x)

在指定位置插入元素。第一个参数指定哪一个位置前插入元素。a.insert(0,x)就是在列表最前方插入,a.insert(len(a),x)则等价于a.append(x)

例:

>>>list1=[1,2,3,4]
>>> list1.insert(1,45)
>>> list1
[1, 45, 2, 3, 4]
list.remove(x)

移除list中值为x的第一个元素,如果没有这样的元素,则返回error,
例:

>>> list1=[1,2,3,4,5,1,2,3,4,5]
>>> list1.remove(1,2)
Traceback (most recent call last):
  File "<pyshell#80>", line 1, in <module>
    list1.remove(1,2)
TypeError: remove() takes exactly one argument (2 given)
>>> list1.remove(1)
>>> list1
[2, 3, 4, 5, 1, 2, 3, 4, 5]
list.pop([i])

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

list.index(x)

Return the index in the list of the first item whose value is x. It is an error if there is no such item.

list.count(x)

Return the number of times x appears in the list.

list.sort(cmp=None, key=None, reverse=False)

Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

list.reverse()

Reverse the elements of the list, in place.

An example that uses most of the list methods:

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。