# 定义一个空列表
nameList = []
namelist = ["小张" , “小王” , "小李"]
list0 = [3, "小郑"] # 列表中的每一项可以是不同的数据类型
# 列表的遍历
for name in namelLst:
print(name)
flag = 0
while flag < len(nameList):
print(flag)
# 在列表的末尾追加项,append方法
nameList.append("小孙") # 对于所添加的项的类型无要求,任意对象都可以,作为一个新元素添加在list末尾
# 将一个列表连接到列表末尾,extend()方法
nameList.extend([3, 2]) #一定是一个列表
# 将一个对象插入到列表的指定位置, insert()方法
nameList.insert(a, b) # a一定是整数,表示下标;b是一个对象
# 删除
del nameList[a] # 删除列表中下标为 a 的元素,修改列表信息保存
nameList.pop() # 出栈,弹出列表最后一个元素,修改列表信息保存
nameList.remove("小王") #从前往后遍历列表,删除遇到的第一个“小王”元素,修改列表信息保存
# 修改
nameList[1] = "小约翰" #nameList[1] 存储的是内存地址,此地址指向“小王”的存储位置,通过本语句使nameList[1]中的地址修改为“小约翰”的地址
# 查
findName in/not in nameList # 判断语句,判断变量findName是否在列表nameList中,返回True或者False
nameList.index("小王", 1, 3) #在列表nameList的下标1到3中,查找“小王”,存在则返回位置下标,不存在则报错;查找范围【1,3)
#列表的方法 count 用于查找列表中是否有要求查找的对象元素,返回个数,没有返回0
>>> nameList = ["呱呱", "哇哇", "小王", "小李", "小王"]
>>> nameList.count("小王")
2
>>> nameList.count("小郑")
0
#排序
>>> nameList = ["呱呱", "哇哇", "小王", "小李", "小王"]
>>> nameList.reverse() # 列表方法reverse对列表中的元素逆序排列
nameList.sort(reverse=True) #排序后逆序保存,即降序排列
>>> nameList
['小王', '小李', '小王', '哇哇', '呱呱']
>>> nameList.extend([1,2,3,4])
>>> nameList
['小王', '小李', '小王', '哇哇', '呱呱', 1, 2, 3, 4]
>>> nameList.sort() # 对列表中元素进行排序,字符串以拼音排序,当列表中既有字符串又有整数时,排序会出错:不支持字符串和整形的排序
#(从第一项开始排序,遇到不同类型数据后排序停止,报错,此时已排序的被存储下来)
Traceback (most recent call last):
File "", line 1, in
nameList.sort()
TypeError: '
1 import random #引入随机模块
2 offices = [[], [], []] #定义三个办公室的列表,每个办公室时存储名字的列表
3 names = ["赵", "钱", "孙", "李", "周", "吴", "郑", "王"] #姓名列表
4
5 #取出每个名字,把每个人随机分配到三个办公室中
6 for name innames:7 i = random.randint(0,2) #随机生成0~2的数字,用于表示第i+1个办公室
8 offices[i].append(name) #添加name到第i+1个办公室中
9 print("把%s到第%d个办公室中"%(name, i+1))10
11 print("-"*30) #打印分隔线
12
13 #打印每个办公室的人数
14 i =015 for office inoffices:16 print("第%d个办公室的人数为%d"%(i+1,len(office)))17 i += 1
18 for name inoffice:19 print("这个办公室里分别是%s"%name, end="\t")20 print("")21
22 print("*"*30)