pythonfilelist_Python学习笔记文件操作list列表操作

随笔记录方便自己和同路人查阅。

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'))

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值