码迷,mamicode.com
首页 > 编程语言 > 详细

python中List操作

时间:2014-09-17 16:48:32      阅读:299      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   os   ar   for   

传送门 官方文件地址

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:

python中List操作

标签:des   style   blog   http   color   io   os   ar   for   

原文地址:http://www.cnblogs.com/fei-hsueh/p/3977467.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!