Python中的列表是一种有序的结合。
列表内的元素可以增加、删除,并且不需要有相同的数据类型。列表是用方括号 + 逗号分隔值:
list1 = ['tencent', 'google', 1688, 'tiktok']
1.list函数
如果对字符串赋值后想要改变字符串中的某个值,因为字符串不能像列表一样可更改,如果想改变这时候可以利用 list 函数,如下:
ll=list('hello')
ll[2]='5'
ll
输出:
['h', 'e', '5', 'l', 'o']
2.len函数
返回列表中的元素个数
list = ['tencent', 'google', 1688, 'tiktok']
len(list)
输出:
4
3.max函数
返回列表中的最大值
nums = [0,2,4,6,8,10]
max(nums)
输出:
10
4.min函数
返回列表中的最小值
nums = [0,2,4,6,8,10]
min(nums)
输出:
0
5.append方法
在列表的末尾增加新的元素
list = ['tencent', 'google', 1688, 'tiktok']
list.append('XiaoMi')
list
输出:
['tencent', 'google', 1688, 'tiktok', 'XiaoMi']
6.count方法
count方法用来统计列表中某个元素出现的次数
num = [1, 2, 3, 4, 5, 5, 5, 5, 6]
num.count(5)
输出:
4
统计字母a出现的次数
name = ['a','a','abf','ark','nhk']
name.count('a')
输出:
2
7.index方法
index方法用来在列表中找出某个元素第一个匹配到的索引位置
content = ['where','who','lisi','content','who']
content.index('content')
输出:
3
8.insert方法
insert方法用于在列表中插入对象
num = [1,2,5,6,7]
num.insert(2,3)
num
[1, 2, 3, 5, 6, 7]
9.pop方法
pop方法用于移除列表中的最后一个元素,并返回这个元素值
x = [1,2,3]
x.pop()
3
x
[1, 2]
10.remove方法
remove方法用于移除列表中第一个匹配到的元素
content = ['where', 'who', 'lisi', 'cntent', 'who', 'who']
content.remove('who')
content
['where', 'lisi', 'cntent', 'who', 'who']
11.reverse方法
reverse方法用于反转函数中的元素
x = [1, 2, 3]
x.reverse()
x
[3, 2, 1]
12.sort方法
sort方法用于给列表中的元素顺序排序
x = [2,3,5,6,1,4,7]
x.sort()
x
[1, 2, 3, 4, 5, 6, 7]
13.clear方法
clear方法用来清空列表
list = ['tencent', 'google', 1688, 'tiktok', 'XiaoMi']
list.clear()
list
输出:
[]
14.copy方法
copy方法用来复制列表
list = ['tencent', 'google', 1688, 'tiktok', 'XiaoMi']
listcopy = list.copy()
listcopy
输出
['tencent', 'google', 1688, 'tiktok', 'XiaoMi']