2021-07-01

list有一些非常有用的方法,比如append,extend,insert,remove,pop,index,count,sort,reverse,copy等。

举个例子:

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
 fruits.count('apple')
2
 fruits.count('tangerine')
0
 fruits.index('banana')
3
fruits.index('banana', 4)  # Find next banana starting a position 4
6
 fruits.reverse()
fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
 fruits.append('grape')
 fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
 fruits.sort()
 fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
 fruits.pop()
'pear'

列表作为栈使用
栈的特点是后进先出,而列表为我们提供了append和pop方法,所以使用列表来实现栈是非常简单的:

 stack = [3, 4, 5]
 stack.append(6)
 stack.append(7)
 stack
[3, 4, 5, 6, 7]
 stack.pop()
7
 stack
[3, 4, 5, 6]
 stack.pop()
6
stack.pop()
 stack
[3, 4]

列表作为队列使用
队列的特点是先进先出,但是使用列表在队列头部插入元素是很慢的,因为需要移动所有的元素。

我们可以使用 collections.deque 来快速的从两端操作:

 from collections import deque
 queue = deque(["Eric", "John", "Michael"])
 queue.append("Terry")           # Terry arrives
 queue.append("Graham")          # Graham arrives
 queue.popleft()                 # The first to arrive now leaves
'Eric'
 queue.popleft()                 # The second to arrive now leaves
'John'
 queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值