python --整理数据结构(列表)

该整理来源于:https://www.runoob.com/python3/python3-data-structure.html

列表

python中列表是可变的,这是它区别于字符串和元组的最重要的特点了:

列表可被修改,字符串和元组不行??

以下介绍列表的一些常用方法

 1 list = [5,2,4,3,1,6]
 2 list.append(7)  #把一个元素添加到列表的结尾
 3 print(list)
 4 list.extend([8]) #通过添加指定列表的所有元素来扩充列表
 5 print(list)
 6 list.insert(1,0) #list.insert(i,x)通过在指定的位置加入新的元素,i是准备插入到那个元素的索引
 7 print(list)
 8 list.remove(0)  #删除列表中为0的元素,若没有这个元素,则会报ValueError: list.remove(x): x not in list
 9 print(list)    
10 list.pop(6) #从列表的指定的位置移除元素,并将其返回,没有指定,就返回最后一个元素
11 print(list)
12 list.pop()
13 print(list)
14 list.index(1) #返回列表中第一个值为1的元素的索引,没有匹配则会ValueError: 0 is not in list
15 print(list)
16 list.sort() #排序
17 print(list)
18 list.reverse() #倒排列表中的元素
19 print(list)
20 list.copy()  #返回列表中的潜复制,等于a[:]
21 print(list) 
22 list.clear()  #清空列表
23 print(list)
 1 [5, 2, 4, 3, 1, 6, 7]
 2 [5, 2, 4, 3, 1, 6, 7, 8]
 3 [5, 0, 2, 4, 3, 1, 6, 7, 8]
 4 [5, 2, 4, 3, 1, 6, 7, 8]
 5 [5, 2, 4, 3, 1, 6, 8]
 6 [5, 2, 4, 3, 1, 6]
 7 [5, 2, 4, 3, 1, 6]
 8 [1, 2, 3, 4, 5, 6]
 9 [6, 5, 4, 3, 2, 1]
10 [6, 5, 4, 3, 2, 1]
11 []
View Code

把列表当做堆栈使用

其中,注意append(),pop():

列表方法使得列表可以很方便的作为一个堆栈来使用,堆栈作为特定的数据结构,最先进入的元素最后一个释放(先进后出)。

用append()方法可以把一个元素添加到堆栈顶,用不指定索引的pop()方法把一个元素从堆栈中释放。

>>> list = [1,2,3,4,5]
>>> list.append(7)
>>> list.append(8)
>>> list.pop()
8
>>> list.pop()
7

把列表当做队列使用

在队列里第一个加入的元素,第一个取出来

>>> from collections import deque
>>> queue = deque(["claire","alice","eric"])
>>> queue.append("nancy")
>>> queue.append("toby")
>>> queue.popleft()
'claire'
>>> queue.popleft()
'alice'
>>> queue()
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    queue()
TypeError: 'collections.deque' object is not callable
>>> queue
deque(['eric', 'nancy', 'toby'])

列表推导式

通常应用程序将一些操作应用于某个序列的元素,用其获得的结果作为生成新的列表的元素,或者根据确定的判定条件创建子序列。

每个列表推导式都在for之后跟一个表达式,然后有零到多个for或者if子句。返回的结果是一个根据表达从其后的for和if上下文环境中生成的列表,如果希望表达式推导出一个元组,就必须使用括号。以下是例子:

>>> list = [2,4,6,8]
>>> [3*x for x in list]
[6, 12, 18, 24]
>>> [[x,x+1,x*3]for x in list]
[[2, 3, 6], [4, 5, 12], [6, 7, 18], [8, 9, 24]]
>>> student = ["claire","gigi","hellen"]
>>> [x.strip() for x in student]
['claire', 'gigi', 'hellen']
>>> [2+x for x in list if x < 3]
[4]
>>> [2*i for i in list if i > 1]
[4, 8, 12, 16]
>>> 

实力展示将3*4的矩阵,演变成4*3的矩阵

>>> matrix = [
    [1,2,3,4],
    [2,3,4,5],
    [3,4,5,6],
]
>>> [[row[i]for row in matrix] for i in range(4)]
    
[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]

 

转载于:https://www.cnblogs.com/clairedandan/p/10964622.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值