一、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']
本文详细介绍了Python中列表的基本函数如cmp(), len(), min(), max(), list()等的使用方法,并深入探讨了列表方法如append(), count(), extend(), index(), insert(), pop(), remove(), reverse(), sort()等功能与应用场景。
147

被折叠的 条评论
为什么被折叠?



