列表(list)的特性及练习
- 列表的定义及创建
列表的定义:
数组:存储同一种数据类型的集合 a = [1,15,3,8,22…]
列表:“打了激素的数组“,可以存储任意数据类型
2.列表的创建
a = [1,15,2.5,True,'westos']
print(a,type(a))
另外:列表里也可以嵌套列表
a = [1,7,14,[1,2.5,True,'westos']]
print(a,type(a))
- 列表的特性----索引、切片、重复、连接
1.索引
a = ['ssh','ftp','http','maridb']
print(a[0])
print(a[3])
print(a[-1])
2.切片
list[::-1]:翻转
list[1:]:列表中除去第一个元素的其他元素
list[:-1]:列表中除去最后一个元素的其他元素
a = ['ssh','ftp','http','maridb']
print(a[::-1])
print(a[1:])
print(a[:-1])
3.重复
a = ['ssh','ftp','http','maridb']
print(a*2) #重复打印列表2遍
4.连接
a = ['ssh','ftp','http','maridb']
b=['服务']
print(a+b)
- 列表的特性----成员操作符、for循环
1.成员操作符
a = ['ssh','ftp','http','maridb']
print('http' in a)
print('dns' in a)
print('ssh' not in a)
print('dns' not in a)
2.for循环
a = ['ssh','ftp','http','maridb']
for i in a:
print(i)
- 列表元素的增加、删除
1.列表元素的增加
list.append():追加一个元素到列表
list.extend() :拉伸,追加多个元素到列表
list.insert():在指定索引处插入元素
a = ['ssh','ftp','http','maridb']
a.append('WESTOS',)
a.extend(['DNS','WESTOS'])
a.insert(1,'HAHA')
print(a)
2.列表元素的删除
pop():默认弹出列表最后一个元素,也可以指定弹出的指定元素
a = ['ssh','ftp','http','maridb']
a.pop(1)
a.pop()
print(a)
remove():删除列表指定元素
a = ['ssh','ftp','http','maridb']
a.remove('ssh')
a.remove('http',)
print(a)
del:从内存中删除一个元素,del可删除变量
a = ['ssh','ftp','http','maridb']
del a[0]
print(a)
5. 列表元素的查看、排序
1.列表元素的查看
a = ['ssh','ftp','http','maridb']
print(a.count('ssh')) ##查看元素在列表中出现的次数
print(a.index('ssh')) ##查看指定元素的索引值
print(a.index('ssh',0,3)) ##查看指定元素的索引值,指定搜索位置
2.列表元素的排序
列表的排序是按照ASCII码进行排序的
a = ['ssh','ftp','http','maridb']
a.sort(reverse=True)
print(a)
对于数字的排序:
#数字升序排序
a = list(range(0,10))
print(a)
#随机排序
import random
random.shuffle(a)
print(a)
练习一:
要求:假定有下面这样的列表:
names = [‘fentiao’, ‘fendai’, ‘fensi’, ‘apple’]
输出结果为:‘I have fentiao, fendai, fensi and apple.’
s = ['fentiao', 'fendai', 'fensi', 'apple']
s1=s[0:3]
print(s1)
s2=' '.join(s1)
print(s2)
s3=s[3]
print(s3)
print('I have %s and %s.' %(s2,s3 ))