列表的定义
列表:可以存储任意数据类型的集合,一个变量存储多个信息
数组:存储同一种数据类型的集合 scores = [1,2,3]
列表:可以存储任意数据类型的集合
#列表里:可以存储不同的数据类型
li = [1,1.2,True,'hello']
print(li)
print(type(li))
#列表里也可以嵌套列表(列表:本身也是一种数据类型)
li1 = [1,1.2,True,'hello',[1,2,3,4,5]]
print(li1)
print(type(li1))
列表的特性
#索引
print(service[0])
print(service[-1])
#切片
print(service[1:])
print(service[:-1])
print(service[::-1])
#重复
print(service * 3)
#连接
service1 = ['mysql','firewalld']
print(service + service1)
#成员操作符
print('firewalld' in service)
print('firewalld' in service1)
#for循环遍历
for se in service:
print(se)
#列表里嵌套列表
service2 = [['http',80],['ssh',22],['ftp',21]]





列表的添加
service = ['http','ssh','ftp']
#1.
# print(service + ['firewalld'])
#2.append:追加一个元素到列表中
service.append('firewalld')
print(service)
#3.extend:拉伸 追加多个元素到列表中
service.extend(['mysql','firewalld'])
print(service)
#4.insert:在指定索引位置插入元素
service.insert(1,'samba')
print(service)
列表的删除
In [12]: service = ['http','ssh','ftp']
In [13]:
In [13]: service.pop()
Out[13]: 'ftp'
In [14]: service
Out[14]: ['http', 'ssh']
In [15]: service.pop()
Out[15]: 'ssh'
In [16]: service
Out[16]: ['http']
In [17]: service.pop()
Out[17]: 'http'
In [18]: service
Out[18]: []
service = ['http','ssh','ftp']
2.remove:删除指定元素
# a = service.remove('ssh')
# print(service)
# print(a)
3.del关键字 从内存中删除
print(service)
del service
print(service)
列表的修改
service = ['http','ssh','ftp']
#通过索引,重新赋值
service[0] = 'mysql'
print(service)
#通过切片
print(service[:2])
service[:2] = ['samba','ldap']
print(service
列表的查看
service = ['ftp','http','ssh','ftp']
#查看出现的次数
print(service.count('ftp'))
#查看指定元素的索引值(可以指定索引范围查看)
print(service.index('ssh'))
print(service.index('ftp',0,3))
列表的排序


本文深入讲解了Python中列表的基本概念,包括定义、特性、索引、切片、重复与连接等操作,以及如何进行添加、删除和修改元素,最后介绍了列表的查看方法,如计数和查找索引。

863

被折叠的 条评论
为什么被折叠?



