namelist = [] #定义一个空列表 namelist = ["小张","小王","小李"] print(namelist[0]) testlist = [1,"测试"] print(type(testlist[0])) print(type(testlist[1])) #列表中可以存储混合类型增加 append、extend、insert 示例1 append
namelist = ["小张","小王","小李"]
#增加 append 在末尾追加 整体加入
namelist.append("小周")
for name in namelist:
print(name)
示例2 extend
#增加 extend 在末尾追加 依次加入 a = [1,2,3] b = [4,5] a.extend(b) print(a)示例3 insert
#增加 insert 插入 a = [0,1,2] a.insert(1,5) #第一个参数代表下标 第二个是插入元素 print(a)删除 del、pop、remove 示例1 del
#删除 del moviename = ["hello","hi","first"] del moviename[2] print(moviename)示例2 pop
#删除 pop 弹出最后一个元素 moviename = ["hello","hi","first"] moviename.pop() print(moviename)示例3 remove
#删除 remove 指定内容 找到第一个就结束了
moviename = ["hello","hi","first","first"]
moviename.remove("first")
print(moviename)
改
moviename = ["hello","hi","first","first"] moviename[3] = "change" print(moviename)查 示例1
findname = "hi"
moviename = ["hello","hi","first","first"]
if findname in moviename:
print("在列表中")
else:
print("不在列表中")
示例2
a = [“a”,“b”,“c”,“a”,“b”]
print(a.index(“a”,1,4)) #查找指定范围的元素 不包含结束 左闭右开 【)
print(a.count(“b”))
a = [1,2,3,5,4] a.reverse() #反转 a.sort() #升序 a.sort(reverse=True) #降序 print(a)嵌套
#嵌套 schoolName = [["a","b"],["c","d","e"]] print(schoolName[0]) print(schoolName[0][0])将老师随机分配到考场
import random
room = [[],[],[]]
teacherName = ["A","B","C","D","E","F","G","H"]
for name in teacherName:
index = random.randint(0,2)
room[index].append(name)
print(room)
商品列表清单
不断询问用户选择什么,用户选择一个编号,就把对应的商品添加到购物车里,用户输入q,打印商品列表
products = [["iphone",6888],["MacPro",14800],["小米6",2499],["Coffee",31],["Book",60],["Nike",699]]
temps = []
print("-"*6 +"商品列表" +"-"*6)
i=0
j=0
for product in products:
print("%d %s %d"%(i,product[0],product[1]))
i += 1
while True:
product_num = input("请输入想买的商品编号:")
if product_num != "q":
num = int(product_num)
temps.append(products[num])
else:
break
print("-"*6 +"购买列表" +"-"*6)
for temp in temps:
print("%d %s %d"%(j,temp[0],temp[1]))
j += 1



