python 列表函数&方法

本文详细介绍了Python中列表的基本函数如cmp(), len(), min(), max(), list()等的使用方法,并深入探讨了列表方法如append(), count(), extend(), index(), insert(), pop(), remove(), reverse(), sort()等功能与应用场景。

一、python 列表函数

cmp()
比较两个列表的元祖,返回值有1,0,-1

>>> list1 = [1,3,5]
>>> list2 = [1,2,5]
>>> cmp(list1, list2)
1

>>> list1 = [1,3,5]
>>> list2 = [1,3,5]
>>> cmp(list1, list2)
0

>>> list1 = [1,3,5]
>>> list2 = [1,3,6]
>>> cmp(list1, list2)
-1

len()
列表元素的个数

>>> list1 = ['a', 1, 'b', 2, 'c', 3]
>>> len(list1)
6

min()
返回列表元素最小值

>>> list1 = [1, 3, 5, 7, 9]
>>> min(list1)
1

max()
返回列表元素最大值

>>> list1 = [1, 3, 5, 7, 9]
>>> max(list1)
9

list()
将元祖转换为列表

>>> tuple1 = ('a', 'b', 'c', 'd')
>>> list1 = list(tuple1)
>>> list1
['a', 'b', 'c', 'd']

二、python 列表方法

append()
在列表末尾追加新的对象

>>> list1 = [1, 3, 5, 7]
>>> list1.append(9)
>>> list1
[1, 3, 5, 7, 9]

count()
统计某个元素在列表中出现的次数

>>> list1 = ['a', 'a', 'c', 'd', 'p', 'a']
>>> list1.count('a')
3
>>> list1.count('c')
1

extend()
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)

>>> list1 = ['1']
>>> list2 = ['2']
>>> list3 = ['3']
>>> list1.extend(list2)
>>> list1
['1', '2']
>>> list1.extend(list3)
>>> list1
['1', '2', '3']

index()
从列表中找出第一个匹配项的索引位置

>>> list1 = ['zhao', 'qian', 'sun', 'li']
>>> list1.index('zhao')
0
>>> list1.index('sun')
2
>>> list1.index('qian')
1
>>> list1.index('li')
3

insert()
将对象插入列表

>>> list1 = [1, 5, 7, 9]
>>> list1.insert(1,3)
>>> list1
[1, 3, 5, 7, 9]

pop()
移除列表中的某个元素(默认最后一个元素),并返回该元素的值

>>> list1 = [1,2,3,4,5,6,7,8,9]
>>> list1.pop()
9
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8]
>>> list1.pop()
8
>>> list1
[1, 2, 3, 4, 5, 6, 7]

remove()
移除列表中某个值的第一个匹配项

>>> list1 = ['aa', 'bb', 'cc', 'dd', 'ee', 'aa']
>>> list1.remove('aa')
>>> list1
['bb', 'cc', 'dd', 'ee', 'aa']
>>> list1.remove('aa')
>>> list1
['bb', 'cc', 'dd', 'ee']
>>> list1.remove('dd')
>>> list1
['bb', 'cc', 'ee']

reverse()
反向排序列表中的元素

>>> list1 = ['a', 'b', 'c', 'd', 'e']
>>> list1.reverse()
>>> list1
['e', 'd', 'c', 'b', 'a']
>>> list1.reverse()
>>> list1
['a', 'b', 'c', 'd', 'e']

sort()
对原列表进行排序

>>> list1 = ['s', 'o', 'r', 't']
>>> list1.sort()
>>> list1
['o', 'r', 's', 't']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值