了解python中的列表
列表由一系列按特定顺序排列的组合。
列表中的元素是有序的;
列表长度不确定,在使用列表时不需要提前声明长度;
列表中的存储元素类型可以不唯一,元素之间没有任何关系;
列表中可以有重复元素。
列表是python中内置有序可变序列,列表的所有元素放在一对中括号[ ]中,并用逗号分隔开。
创建
使用 list( ) 函数将元素、range对象、字符串或其它类型的可迭代对象类型的数据转换为列表;
使用 = 直接将列表赋值给变量即可创建列表对象。
list = [1,1.2,True,'westos']
print(list,type(list))
# 列表里也可以嵌套列表
list2 = [1,2,3,4,[1,1.2,True,'westos']]
print(list2,type(list2))
特性
索引
正向索引
service=['http','ftp','ssh']
print(service[0])
反向索引
service=['http','ftp','ssh']
print(service[-1])
切片
service=['http','ftp','ssh']
# 切片
print(service[::-1])
print(service[1:])
print(service[:-1])
重复
service=['http','ftp','ssh']
print(service * 3)
成员操作符
service=['http','ftp','ssh']
print('firewalld' in service)
print('ftp' not in service)
for循环
service=['http','ftp','ssh']
or i in service:
print(i)
列表元素的增加
append():追加一个元素到列表
service = ['http','ftp','ssh']
service.append('firewalld')
print(service)
extend():拉伸 追加多个元素到列表
service = ['http','ftp','ssh']
service.extend(['mysql','nfs'])
print(service)
insert():在指定索引处插入元素
service = ['http','ftp','ssh']
service.insert(1,'dns')
print(service)
列表元素的删除
>>> service = ['http','ftp','ssh']
>>> service.pop()##将倒数第一个元素取出
'ssh'
>>> service
['http', 'ftp']
>>> service.pop()
'ftp'
>>> service
['http']
>>> a = service.pop()##将元素取出后赋值给a
>>> service
[]
>>> a
'http'
>>> service
[]
>>> service.pop()##此时列表中没有元素可以取出,所以会报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop from empty list
移走列表中的元素
service = ['http','ftp','ssh']
a = service.remove('ftp')
print(service)
print(a)
取出列表中的元素
删除列表中的元素
列表元素的查看
统计列表中某个元素的个数
service = ['http', 'ftp', 'ssh','myspl','firewall','http']
print(service.count('ssh'))
查看列表中元素存在的索引值(可以指定搜索范围)
service = ['http', 'ftp', 'ssh','myspl','firewall','http']
print(service.index('firewall'))
print(service.index('ftp'))
print(service.index('ssh',0,3))
列表元素的排序
service = ['ftp','ssh','http','mysql','http','ssh']
# 默认按照ascii码进行排序的
service.sort(reverse=True)
print(service)
import random
li = list(range(0,101))
print(li)
random.shuffle(li)
print(li)