1.列表的创建
数值类型:int float (long)
布尔型
字符串
列表(list)
数组:存储同一种数据类型的集和 scores=[1,2,33,44]
列表(打了激素的数组):可以存储任意数据类型的集和
li = [1,2.2,True,'hello']
print(li,type(li))
输出:
[1, 2.2, True, 'hello'] <class 'list'>
列表里面是可以嵌套列表的
li = [1,2,3,False,'python',[1,2,3,4,5]]
print(li,type(li))
import random
li = list(range(10))
random.shuffle(li) #打乱顺序
print(li)
2.列表的特性
service = [‘http’,‘ssh’,‘ftp’]
- 索引
正向索引
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('ftp' in service)
print('firewalld' not in service)
print('ftp' not in service)
- 列表里面嵌套列表
service2 = [['http',80],['ssh',22],['ftp',21]]
索引
print(service2[0][0])
print(service2[-1][1])
3.列表元素的增加
service = [‘http’, ‘ssh’, ‘ftp’]
print(service + [‘firewalld’])
- append:追加,追加一个元素到列表中
service.append('firewalld')
print(service)
- extend:拉伸,追加多个元素到列表中
service.extend(['hello','python'])
print(service)
- insert:在索引位置插入元素
service.insert(0,'firewalld')
print(service)
4.列表元素的删除
- pop
li = [1,2,3,4]
print(li.pop()) ##默认输出最后一个
4
print(li.pop(0)) ##输出索引0对应的元素
1
service = [‘http’, ‘ssh’, ‘ftp’]
- remove
service.remove('ftp') ##删除'ftp'
print(service)
- claer:清空列表里面的所有元素
service.clear() ##输出空列表
print(service)
- del(python关键字) 从内存中删除列表
del service ##直接删除内存,报错
print(service)
print('删除列表第一个索引对应的值:',end='')
del service[1] ##删除‘ssh‘
print(service)
print('删除前两个元素之外的其他元素:',end='')
del service[2:]
print(service)
5.列表元素的修改
service = [‘ftp’,‘http’, ‘ssh’, ‘ftp’]
- 通过索引,重新赋值
service[0] = 'mysql' ##将ftp改为mysql
print(service)
- 通过slice(切片)
service[:2] = ['mysql','firewalld']
print(service)
6.列表元素的查看
service = [‘ftp’,‘http’, ‘ssh’, ‘ftp’,‘ssh’,‘ssh’]
- 查看元素出现的次数
print(service.count('ftp'))
- 查看制定元素的索引值(也可以指定范围)
print(service.index('ssh'))
print(service.index('ssh',4,8))
- 排序查看(按照ascii码进行排序)
print(service.sort(reverse=True))
print(service)
- 对字符串排序不区分大小写
phones = ['alice','bob','harry','Borry']
phones.sort(key=str.lower)
phones.sort(key=str.upper)
print(phones)