1.列表的创建
数组:存储同一种数据类型的集合 scores=[12,13,14]
列表:(打了激素的数组):可以存储任意数据类型的集合
In [1]: name1 = 'tom'
In [2]: name2 = 'lily'
In [3]: name3 = 'bob'
In [4]: name4 ='coco'
In [5]: name1
Out[5]: 'tom'
In [6]: name2
Out[6]: 'lily'
In [7]: name3
Out[7]: 'bob'
In [8]: name = ['tom','lily','bob','cooc']
In [9]: name
Out[9]: ['tom', 'lily', 'bob', 'cooc']
In [10]: type(name)
Out[10]: list
一个变量存储多个信息
"""
# 列表里:可以存储不同的数据类型
li = [1,1.2,True,'hello']
print li
print type(li)
# 列表里面也可以嵌套列表(列表:也是一种数据类型)
li = [1,1.2,True,'hello',[1,2,3,4,5]]
print li
print type(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 'firewalld' in service1
print 'firewalld' not in service
# for循环遍历
print '显示服务'.center(50,'*')
for se in service:
print se
# 列表里嵌套列表
service2 = [['http',80],['ssh',22],['ftp',21]]
# 索引
print service2[0][1]
print service2[-1][1]
# 切片
print service2[:][1]
print service2[:-1][0]
print service2[0][:-1]
3.列表的查看
service = ['http', 'ssh', 'ftp','ftp']
# 查看列表中元素出现的次数
print service.count('ssh')
# 查看指定元素的索引值
print service.index('ssh')
4.列表的排序
service = ['http', 'ssh', 'ftp','ftp']
# # 按照Ascii码进行排序的
service.sort()
print service
service.sort(reverse=True)
print service
phones = ['bob', 'harry', 'Lily', 'Alice']
phones.sort()
# # 对字符串排序不区分大小写
phones.sort(key=str.lower)
phones.sort(key=str.upper)
print phones
import random
li = list(range(10))
print li
# 将原有的列表顺序打乱
random.shuffle(li)
print li
5.列表的增加
service = ['http', 'ssh', 'ftp']
# 1.连接
print service + ['firewalld']
# 2.append:追加 追加一个元素到列表中
service.append('firewalld')
print service
# 3.extend:拉伸 追加多个元素到列表中
service.extend(['mysql', 'firewalld'])
print service
# 4. insert:在指定索引位置插入元素
service.insert(1,'samab')
print service
6.列表的删除
service = ['http', 'ssh', 'ftp']
#1.如果pop()不传递值的时候,默认弹出最后一个元素
print service.pop()
# pop()也可以传递索引值
print service.pop(0)
# 2.remove:删除指定的元素
service.remove('ssh')
print service
# 3.del 关键字 从内存中删除列表
print service
del service
print service
7.列表的修改
# 通过索引,重新赋值
service[0] = 'mysql'
print service
# 通过切片
print service[:2]
service[:2] = ['samba','ladp']
print service