列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作,以[]标识,中间用逗号隔开
names
=
[
‘aa‘
,
"bb"
,
‘cc‘
] #names变量用列表来赋值
列表索引以0开头
names = [‘aa‘,"bb",‘cc‘,‘dd‘,‘ee‘]print(names[0])#aaprint(names[-1])#eeprint(names[:-1])#[‘aa‘, ‘bb‘, ‘cc‘, ‘dd‘]print(names[:])#[‘aa‘, ‘bb‘, ‘cc‘, ‘dd‘, ‘ee‘]print(names[1:3])#[‘bb‘, ‘cc‘]顾头不顾尾print(names[1::2])#[‘bb‘, ‘dd‘]步长为2
append()追加,可以是任意参数,作用是往已有列表中添加元素,如果添加的是列表,就被当成一个元素存在原列表中,只使list长度增加1.
names = [‘aa‘,"bb",‘cc‘,‘dd‘,‘ee‘]#names.append(‘ff‘)print(names)#[‘aa‘, ‘bb‘, ‘cc‘, ‘dd‘, ‘ee‘, ‘ff‘]names.append(["d1","d2"])print(names)#[‘aa‘, ‘bb‘, ‘cc‘, ‘dd‘, ‘ee‘, [‘d1‘, ‘d2‘]]
insert()插入 insert(index,obj)列表与方法之间用点号相隔,括号内需要添入的参数分别是索引和要插入的元素
names = [‘aa‘,"bb",‘cc‘,‘dd‘,‘ee‘]names.insert(2,"a1")print(names)#[‘aa‘, ‘bb‘, ‘a1‘, ‘cc‘, ‘dd‘, ‘ee‘]
修改
names = [‘aa‘,"bb",‘cc‘,‘dd‘,‘ee‘]names[2]="a1"print(names)#[‘aa‘, ‘bb‘, ‘a1‘, ‘dd‘, ‘ee‘]
删除
names = [‘aa‘,"bb",‘cc‘,‘dd‘,‘ee‘]
方式1 del:
del names[2]print(names)#[‘aa‘, ‘bb‘, ‘dd‘, ‘ee‘]
方式2 remove:names.remove("cc")print(names)#[‘aa‘, ‘bb‘, ‘dd‘, ‘ee‘] 方式3 pop:names.pop()print(names)#[‘aa‘, ‘bb‘, ‘cc‘, ‘dd‘]默认是删除最后一个,指定索引就删除对于索引的元素
这里按索引names.pop(2)print(names)#[‘aa‘, ‘bb‘, ‘dd‘, ‘ee‘]
扩展extend
names = [‘aa‘,"bb",‘cc‘,‘dd‘,‘ee‘]aa = [1,2,3]names.extend(aa)print(names,aa)#[‘aa‘, ‘bb‘, ‘cc‘, ‘dd‘, ‘ee‘, 1, 2, 3] [1, 2, 3]
复制copy
names = [‘aa‘,"bb",‘cc‘,‘dd‘,‘ee‘]names2 = names.copy()print(names2)#[‘aa‘, ‘bb‘, ‘cc‘, ‘dd‘, ‘ee‘]
计数count
names = [‘aa‘,"bb",‘cc‘,‘dd‘,‘aa‘]names2 = names.count("aa")print(names2)#2
清空clear
names = [‘aa‘,"bb",‘cc‘,‘dd‘,‘aa‘]names.clear()print(names)#[]
排序sort、reverse
names = [‘1aa‘,"Cbb",‘1cc‘,‘dd‘,‘aa‘]names.sort()print(names)#[‘1aa‘, ‘1cc‘, ‘Cbb‘, ‘aa‘, ‘dd‘]按照ASCII码表的顺序来排序names2 = [‘aa‘,"bb",‘cc‘,‘dd‘,‘ee‘]names2.reverse()print(names2)#[‘ee‘, ‘dd‘, ‘cc‘, ‘bb‘, ‘aa‘]
下标index
names = [‘aa‘,"bb",‘cc‘,‘dd‘,‘ee‘]print(names.index(‘bb‘))#1
元组
元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表
names = (‘aa‘,"bb",‘aa‘,‘dd‘,‘ee‘)print(names.count("aa"))#2print(names.index(‘bb‘))#1
时间: 2024-10-12 15:36:15