一、列表的创建
数组:存储同一种数据类型的集合 scores = [1,2,3]
列表:可以存储任意数据类型的集合
lie = [6,8,'s','q',True] # 定义列表,有不同类型的数据
print(lie) # 输出列表
print(type(lie)) # 查看列表内容# 列表里也可以嵌套列表
列表里也可以嵌套列表(列表:本身也是一种数据类型)
li = [1,2,3,False,'python',[1,2,3,4,5]]
print(li,type(li))
输出结果:
[1, 2, 3, False, 'python', [1, 2, 3, 4, 5]] <class 'list'>
随机输出一个乱序的列表
import random
li = list(range(10))
# 快速生成列表
random.shuffle(li)
print(li)
结果:
[6,4,5,3,9,8,1,0,7,2] ##乱序
二、列表的特性
索引
service = ['http','ssh','lftp']
print(service[0])
print(service[-1])
输出结果:
http
lftp
切片
service = ['http','ssh','lftp']
print(service[1:])
print(service[:-1])
print(service[::-1])
输出结果:
['ssh', 'lftp']
['http', 'ssh']
['lftp', 'ssh', 'http']
重复
service = ['http','ssh','lftp']
print(service * 3)
输出结果:
['http', 'ssh', 'ftp', 'http', 'ssh', 'ftp', 'http', 'ssh', 'lftp']
连接
service = ['http','ssh','lftp']
service1 = ['mysql','firewalld']
print(service + service1)
输出结果:
['http', 'ssh', 'lftp', 'mysql', 'firewalld']
成员操作符
service = ['http','ssh','ftp']
print('firewalld' in service)
print('firewalld' in service1)
输出结果:
False
True
for循环 (迭代)
service = ['http','ssh','lftp']
for se in service:
print(se)
输出结果:
http
ssh
lftp
列表里嵌套列表
service2 = [['http',80],['ssh',22],['lftp',21]]
#1.索引
print(service2[1][1])
print(service2[-1][1])
#2.切片
print(service2[:][1])
print(service2[:-1][0])
print(service2[::-1][0])
print(service2[0][:-1])
输出结果:
22
21
['ssh', 22]
['http', 80]
['lftp', 21]
['http']
三、列表的应用-判断季节
根据用于指定月份,打印该月份所属的季节。
提示:3,4,5 春季 6,7,8 夏季 9,10,11 秋季 12, 1, 2 冬季
month=int(input('请输入月份:'))
if month in [3,4,5]:
print('%d月是春季' %month)
elif month in [6,7,8]:
print('%d月是夏季' %month)
elif month in [9,10,11]:
print('%d月是秋季' %month)
elif month in [12,1,2]:
print('%d月是冬季' %month)
else:
print('请输入正确的月份')
四、列表的应用-连接列表
假定有下面的列表:
names = [‘fentiao’,‘fendai’,‘fensi’,‘apple’]
输出结果为:‘I have fentiao, fendai, fensi and apple.’
names = ['fentiao','fendai','fen