列表是可变类型,列表中存放的数据是可以进行修改的,增删改
enumerate()实现带下标索引的遍历
chars = ['a', 'b', 'c', 'd']
>>> for i, chr in enumerate(chars):
... print i, chr
...
0 a
1 b
2 c
3 d
>>> for i, chr in enumerate(chars):
... print i, chr
...
0 a
1 b
2 c
3 d
1.添加元素(append,extend,insert)
1)append可以向列表中添加元素
2)extend可以将另一个集合中的元素逐一添加到列表中。
3)insert 在指定位置index前插入元素
2.修改元素、:通过下标来确定。
3.查找元素:in,not in,index,count就是看看指定的元素是否存在。
index和count与字符串中的用法相同。
>>> a.index('a', 1, 4)
3
>>> a.count('b')
2
>>> a.count('d')
0
4.删除元素del。pop,remove
1)-del 根据下标进行删除
2)pop删除最后一个元素
3)remove根据元素的值进行删除
列表的嵌套:一个列表中的元素又是一个列表。
给学校的3个办公室随机分配8位老师的例子
import random
# 定义一个列表用来保存3个办公室
offices = [[],[],[]]
# 定义一个列表用来存储8位老师的名字
names = ['A','B','C','D','E','F','G','H']
i = 0
for name in names:
index = random.randint(0,2)
offices[index].append(name)
i = 1
for tempNames in offices:
print('办公室%d的人数为:%d'%(i,len(tempNames)))
i+=1
for name in tempNames:
print("%s"%name,end='')
print("\n")
print("-"*20)