python3 列表函数和用法

以下讲解python3中列表函数的用法

python列表操作符

列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表

操作符描述结果
['Hi!'] * 4重复['Hi!', 'Hi!', 'Hi!', 'Hi!']
[1, 2, 3] + [4, 5, 6]组合[1, 2, 3, 4, 5, 6]
3 in [1, 2, 3]元素是否存在于列表中True
for x in [1, 2, 3]: print(x, end=" ")迭代1 2 3

python列表函数用法

序号函数描述
1len(list)列表元素个数
2max(list)返回列表元素最大值
3min(list)返回列表元素最小值
4list(seq)将元组转换为列表
5list.append(obj)在列表末尾添加新的对象
6list.count(obj)统计某个元素在列表中出现的次数
7list.extend(seq)在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
8list.index(obj)从列表中找出某个值第一个匹配项的索引位置
9list.insert(index,obj)将对象插入列表
10list.pop(index=-1)移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
11list.remove(obj)移除列表中某个值的第一个匹配项
12list.reverse()反向列表中元素
13list.sort(key=none,reverse=false)对原列表进行排序
14list.clear()清空列表
15list.copy()复制列表

列表函数实例如下:

1.len(list)

>>> dpc = [1,2,3]
>>> len(dpc)
3

2.max(list)

>>> dpc = ['a','b','c']
>>> max(dpc)
'c'

3.min(list)

>>> dpc = ['a','b','c']
>>> min(dpc)
'a'

4.list(seq)

>>> str = 'dpc'
>>> list(str)
['d', 'p', 'c']
>>> tuple = (1,2,3)
>>> list(tuple)
[1, 2, 3]

5.list.append(obj

>>> dpc = ['www.baidu.com']
>>> dpc.append('www.dpc.com')
>>> print (dpc)
['www.baidu.com', 'www.dpc.com']

6.list.count(obj)

>>> dpc = ['a','b','a','c']
>>> print (dpc.count('a'))
2
>>> print (dpc.count('b'))
1
>>> print (dpc.count('c'))
1

7.list.extend(seq)

>>> list1 = [1,2,3]
>>> list2 = [4,5,6]
>>> list1.extend(list2)
>>> print (list1)
[1, 2, 3, 4, 5, 6]

8.list.index(obj)

>>> dpc = ['How','are','you']
>>> dpc.index('How')
0
>>> dpc.index('are')
1
>>> dpc.index('you')
2

9.list.insert(index,obj)

参数描述
index对象obj需要插入的索引位置。
obj要插入列表中的对象。
>>> dpc = [1,2,3]
>>> dpc.insert(3,4)
>>> print (dpc)
[1, 2, 3, 4]

10.list.pop(index=-1)

>>> dpc = ['a','b','c']
>>> dpc.pop()
'c'
>>> dpc.pop(0)
'a'
>>> print (dpc)
['b']

11.list.remove(obj)

>>> dpc = [1,2,3,4]
>>> dpc.remove(2)
>>> print (dpc)
[1, 3, 4]

12.list.reverse()

>>> dpc = [1,2,3,4]
>>> dpc.reverse()
>>> print (dpc)
[4, 3, 2, 1]

13.list.sort(key=none,reverse=false)

参数描述
key主要是用来进行比较的元素
reverse排序规则,reverse = True 降序, reverse = False 升序(默认)
>>> dpc = [1,2,3,4]
>>> dpc.sort(reverse=True)
>>> dpc
[4, 3, 2, 1]
>>> dpc = ['a','b','c']
>>> dpc.sort(reverse=True)
>>> dpc
['c', 'b', 'a']
#int和str同时进行比较会报错
>>> dpc = [1,2,3,'a','b','c']
>>> dpc.sort(reverse=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值