python中的列表元素

列表可以存储任意数据类型

列表的表示类型的查看

sit = [1,2,3.4,True,'fangyuan']
print(lsit)
priint(type(list))
#打印结果
[1, 2, 3.4, True, 'fangyuan']
<class 'type'>  

切片

service = ['http','ftp','ssh']
print(service[0])
print(service[::-1])
print(service[1:])
print(service[:-1])

#打印结果
http
['ssh', 'ftp', 'http']
['ftp', 'ssh']
['http', 'ftp']

追加元素

#追加元素
service = ['http','ftp','ssh']
service.append('firewall')
print(service)

#拉伸增加多个元素
service.extend(['mysql','nfs'])
print(service)

#指定索引处添加
service.insert(1,'https')
print(service)

#打印结果
['http', 'ftp', 'ssh', 'firewall']
['http', 'ftp', 'ssh', 'firewall', 'mysql', 'nfs']
['http', 'https', 'ftp', 'ssh', 'firewall', 'mysql', 'nfs']

删除

service = ['http','ftp','ssh','https']
service.pop()  #弹出最后一个元素
print(service)

service.pop(0)  #删除索引元素
print(service)

service.remove('ssh')  #删除指定元素
print(service)

del service[0]   #从内存中删除一个元素
print(service)

#打印结果
['http', 'ftp', 'ssh']
['ftp', 'ssh']
['ftp']
[]

元素的查看

service = ['http','ftp','ssh','http','ftp','ssh']
# 查看元素在列表中出现的次数
print(service.count('ftp'))
# 查看指定元素的索引值(可以指定索引范围)
print(service.index('ssh'))
print(service.index('ssh',4,7))

#打印结果
2
2
5

排序

service = ['http','ftp','ssh']
# 默认按照Ascii码进行排序
service.sort(reverse=True)
print(service)

phones = ['Tom','alice','bob','Borry']
phones.sort(key=str.upper)
#统一大小写排序
print(phones)

#打印结果
['ssh', 'http', 'ftp']
['alice', 'bob', 'Borry', 'Tom']

修改

service = ['ftp','http','ftp','ssh','mysql']
# 通过索引值,重新赋值
service[0] = 'samba'
print(service)

# 通过切片赋值
print(service[:2])
service[:2] = ['mysql','nginx','nfs']
print(service)

#打印结果
['samba', 'http', 'ftp', 'ssh', 'mysql']
['samba', 'http']
['mysql', 'nginx', 'nfs', 'ftp', 'ssh', 'mysql']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值