Home > Backend Development > Python Tutorial > Python常用列表数据结构小结

Python常用列表数据结构小结

WBOY
Release: 2016-06-16 08:43:01
Original
1271 people have browsed it

本文汇总了Python列表list一些常用的对象方法,可供初学者参考或查询,具体如下:

1.list.append(x)

把元素x添加到列表的结尾,相当于a[len(a):] =[x],代码如下:

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

Copy after login

2. list.extend(L)

将一个列表中的所有元素都添加到另一个列表中,相当于 a[len(a):] = L,代码如下:

>>> a
[1, 2, 3, 4, 5, -2]
>>> L=[5,9,7]
>>> L
[5, 9, 7]
>>> a.extend(L)
>>> a
[1, 2, 3, 4, 5, -2, 5, 9, 7]

Copy after login

3. list.insert(i,x)

将元素x,插到索引号i之前,代码如下:

>>> a
[1, 2, 3, 4, 5, -2, 5, 9, 7]
>>> a.insert(0,-3)
>>> a
[-3, 1, 2, 3, 4, 5, -2, 5, 9, 7]
>>> a.insert(len(a),10)
>>> a
[-3, 1, 2, 3, 4, 5, -2, 5, 9, 7, 10]

Copy after login

4. list.remove(x)

删除元素x(第一次出现的),代码如下:

>>> a
[-3, 1, 2, 3, 4, 5, -2, 5, 9, 7, 10]
>>> a.append(1)
>>> a
[-3, 1, 2, 3, 4, 5, -2, 5, 9, 7, 10, 1]
>>> a.remove(1)
>>> a
[-3, 2, 3, 4, 5, -2, 5, 9, 7, 10, 1]

Copy after login

5. list.count(x)

计算元素x出现的次数,代码如下:

>>> a
[-3, 2, 3, 4, 5, -2, 5, 9, 7, 10, 1]
>>> a.count(3)
1
Copy after login

6. list.sort()

对列表元素进行排序,代码如下:

>>> a.sort()
>>> a
[-3, -2, 1, 2, 3, 4, 5, 5, 7, 9, 10]
Copy after login

7. list.reverse()

倒排列表中元素,代码如下:

>>> a
[-3, -2, 1, 2, 3, 4, 5, 5, 7, 9, 10]
>>> a.reverse()
>>> a
[10, 9, 7, 5, 5, 4, 3, 2, 1, -2, -3]
Copy after login

8. list.index(x)

返回表中第一个出现值为x的索引,代码如下:

>>> a
[10, 9, 7, 5, 5, 4, 3, 2, 1, -2, -3]
>>> a.index(9)
1
Copy after login

9. list.pop(i)

从列表指定位置i删除元素,并将此元素返回,若未指定位置则删除列表最后一位元素,并将此元素返回。代码如下:

>>> a
[10, 9, 7, 5, 5, 4, 3, 2, 1, -2, -3]
>>> a.pop(0)
10
>>> a
[9, 7, 5, 5, 4, 3, 2, 1, -2, -3]
>>> a.pop()
-3
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template