1.列表的创建.py
list = [1,1.2,True,'westos']
print(list,type(list))
列表里也可以嵌套列表
list2 = [1,2,3,4,[1,1.2,True,'westos']]
print(list2,type(list2))
2.列表的特性
service = ['http','ftp','ssh']
#索引
#正向索引
print(service[0])
# 反向索引
print(service[-1])
# 切片
print(service[::-1])
print(service[1:])
print(service[:-1])
# 重复
print(service * 3)
# 成员操作符
print('firewalld' in service)
print('ftp' not in service)
# for循环
for i in service:
print(i)
eg:
names = ['fentiao', 'fendai', 'fensi', 'apple']
print('I have ' + ','.join(names[:-1]) + ' and ' + names[-1])
3.列表元素的增加
service = ['http','ftp','ssh']
# append():追加一个元素到列表
service.append('firewalld')
print(service)
# extend():拉伸 追加多个元素到列表
service.extend(['mysql','nfs'])
print(service)
# insert():在指定索引处插入元素
service.insert(1,'dns')
print(service)
4.列表元素的删除.py
service = ['http','ftp','ssh']
a = service.remove('ftp')
print(service)
print(a)
# 从内存中删除一个元素
del service[1]
print(service)
5. 列表元素的查看
service = ['http','ftp','ssh','mysql','ssh','http']
# 查看元素在列表中出现的位置
print(service.count('ssh'))
# 查看指定元素的索引值(可以指定搜索范围)
print(service.index('ssh'))
print(service.index('ssh',4,7))
6.列表元素的排序
import random
service = ['ftp','ssh','http','mysql','http','ssh']
# 默认按照ascii码进行排序的
service.sort(reverse=True)
print(service)
li = list(range(0,101))
print(li)
random.shuffle(li)
print(li)
eg:
问题描述:按照下面的要求实现对列表的操作:
产生一个列表,其中有 40 个元素,每个元素是 50 到 100 的一个随机整数
如果这个列表中的数据代表着某个班级 40 人的分数,请计算成绩低于平均分的学生人数
对上面的列表元素从大到小排序并输出li.sort(reverse=True)
"""
import random
score = []
# 循环40次
for count in range(40):
num = random.randint(50,100)
score.append(num)
print('40人的分数为:',score)
sum_score = sum(score)
print(sum_score)
ave_num = sum_score/40
# 将小于平均成绩的成绩找出来 组成新的列表 并求列表的长度
less_ave = []
for i in score:
if i < ave_num:
less_ave.append(i)
long = len(less_ave)
print(long)
print('平均分数为:%.1f' %(ave_num))
print('有%d个学生低于平均分数:'%(long))
score.sort(reverse=True)
print('排序结果:',score)
7.列表元素的修改.py
service = ['https','ftp','ssh','mysql']
# 通过索引,重新赋值
service[0] = 'http'
print(service)
# 通过切片赋值
service[:2] = ['samba','dns','firewalld']
print(service)