随笔记录方便自己和同路人查阅。
names = ["cat","rat","lion","terger","cow","hen",'#$%^&','NIHASO','你好']
names = []
以上都是列表,使用[]对变量赋值就是列表
--------------------------------------------我是无耻的分割线--------------------------------------------------------------
从左到右下标是从0开始的,第一个是0
从右到左下标是从-1开始的,第一个是-1
--------------------------------------------我是无耻的分割线--------------------------------------------------------------
1、列表的取值
(1)打印列表的所有内容
names = ["cat","rat","lion","terger","cow","hen",'#$%^&','NIHASO','你好']
print(names)#取所有值
运行结果:
(2)根据下标从左到右打印前4个值
names = ["cat","rat","lion","terger","cow","hen",'#$%^&','NIHASO','你好']
print(names[0:4])#取前四个,根据下标取值时,4本身不会被取出
print(names[:4])
运行结果:根据运行结果可看出,以上两种方法得到的结果是相同的
(3)根据下标打印最后4个值
names = ["cat","rat","lion","terger","cow","hen",'#$%^&','NIHASO','你好']
print(names[-5:-1])#取后四个,根据倒叙取值时,-1本身不会被取出
print(names[-4:])#从-4到-1全部取出
运行结果:
2、列表的增加
(1)append()函数,此函数的作用是在列表的最后面追加要写入的内容
names = ["cat","rat","lion","cow","hen"]
names.append("bat")#追加写入 在列表最后添加一个新的
print(names)
运行结果:
(2)insert()函数,此函数可指定插入的位置
names = ["cat","rat","lion","cow","hen"]
names.insert(1,"bat")#追加写入 在列表最后添加一个新的
print(names)
运行结果:
3、列表的删除
(1)remove()函数,此函数可指定要删除的内容
names = ["cat","rat","lion","cow","hen"]
names.remove("rat")#根据名字删除
print(names)
运行结果:
(2)del()函数,此函数可指定要删除的位置
names = ["cat","rat","lion","cow","hen"]
del names[0:2]#根据下标删除内容
print(names)
运行结果:
4、列表的改变
names = ["cat","rat","lion","cow","hen"]
names[0] = 'Mao'
print(names)
运行结果:
5、统计列表中重复内容
names = ["cat","cat","cat","lion","cow","hen"]
print(names.count('cat'))
运行结果: