Python之列表和元组

来源:互联网 发布:集贤一中网络空间主页 编辑:程序博客网 时间:2024/05/29 18:47

列表常用方法

>>> a = [1, 4, 6, 7, 8, 3, 6, 7, 6] #创建列表>>> a.append(4)#列表末尾插入元素>>> a[1, 4, 6, 7, 8, 3, 6, 7, 6, 4]>>> a.insert(2,6)#列表特定位置插入元素>>> a[1, 4, 6, 6, 7, 8, 3, 6, 7, 6, 4]>>> a.count(6)#列表中某个元素出现的次数4>>> a.remove(3)#删除特定位置的元素>>> a[1, 4, 6, 6, 7, 8, 6, 7, 6, 4]>>> a.reverse()#反转列表>>> a[4, 6, 7, 6, 8, 7, 6, 6, 4, 1]>>> b = [12, 11, 15, 19]>>> a.extend(b)#将列表b添加到列表a末尾>>> a[4, 6, 7, 6, 8, 7, 6, 6, 4, 1, 12, 11, 15, 19]>>> a.sort()#列表排序>>> a[1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 11, 12, 15, 19]>>> del a[3] #del关键字删除列表中特定位置的元素>>> a[1, 4, 4, 6, 6, 6, 7, 7, 8, 11, 12, 15, 19]>>> 

列表用作栈和队列

栈: LIFO(Last in first out)

>>> c = [1, 2, 3, 4, 5, 6]>>> c.pop() #pop(i)可以将第i个元素弹出6>>> c[1, 2, 3, 4, 5]>>> c.pop()5>>> c[1, 2, 3, 4]>>> c.append(7)>>> c[1, 2, 3, 4, 7]>>> 

队列:FIFO (First in first out)

[1, 2, 3, 4, 7]>>> c.append(8)>>> c[1, 2, 3, 4, 7, 8]>>> c.pop(0)1>>> c[2, 3, 4, 7, 8]>>>

列表推倒式:

>>> d = [ x*x for x in range(10)]>>> d[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]>>> [(x, y) for x in [1,2,4] for y in [1, 3, 4] if x!=y][(1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (4, 1), (4, 3)]>>> a = [x*x for x in [ y for y in range(4)]]#推倒式嵌套>>> a[0, 1, 4, 9]>>> 

列表切片:

>>> a = [1, 23, 100, 'hello', 'python']>>> a[1]23>>> a[-1]#索引为负数时将从末尾开始计数'python'>>> a[0:-1]#把a切成不同部分这个操作成为切片[1, 23, 100, 'hello']>>> a[2:-2]#表示从头到尾数数索引为2与从尾到头数索引为2之间的元素[100]>>> a[:]#索引省略时第一个索引表示0,第二个为列表的长度[1, 23, 100, 'hello', 'python']>>> a[:-1][1, 23, 100, 'hello']>>> a[2:][100, 'hello', 'python']>>> a[1::2]#设置步长,表示从索引为1到末尾每两个元素取一个元素[23, 'hello']>>> a[:100]#当索引超过列表的长度时自动用列表长度替代[1, 23, 100, 'hello', 'python']>>> a[100:3]#第一个索引大于第二个索引时返回空列表[]>>> 

元组:

如果要排序一个元组,因为元组时不可变对象,所以需要先将元组用list()方法转为列表,然后用L.sort()排序。或者直接用sorted()排序,然后将返回的列表转为元组

>>> a = 'python' , 'is' , 'cool'#创建元组>>> a('python', 'is', 'cool')>>> x, y, z = a#元组a给x,y,z赋值>>> a('python', 'is', 'cool')>>> x'python'>>> y'is'>>> z'cool'>>> del a[0]#元组是不可变类型,意味着不能删除,添加,编辑Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 'tuple' object doesn't support item deletion>>> b = 'hello',#创建只有一个元素的元组时元素后要加逗号>>> b('hello',)>>> 

The Python Standard Library截图:

这里写图片描述

原创粉丝点击