python之列表(list)
1、格式
namelist = [] #定义一个空列表 namelist2 = ["tom", "marry", "Bob"] tlist = [3, 3.22, "Bob"]
可以是不同的数据类型
2、遍历输出列表:
namelist2 = ["tom", "marry", "Bob",6,3,1,1] print(namelist2) print(namelist2[0:4]) #从位置0到4(左开右闭),包括 0 1 2 3 四个位置 print(namelist2[0:6:2]) #从位置0到6(左开右闭),跨步值为2,分别为 0 2 4三个位置 print("-"*10) for name in namelist2: print(name)
3、列表之增删改查
1)增加:追加、扩散追加、插入
append
namelist2 = ["tom", "marry", "Bob",6,3,1,1] #追加 print("追加前:名单数据") for name in namelist2: print(name) a=input("请输入追加的名字:") namelist2.append(a) print("追加后:名单数据") for name in namelist2: print(name)
extend
a = [1, 2] b = ["jjj", "nknk", 2] a.append(b) # 将一个数组当作一个元素加入 print(a) a.extend(b) # 拆散逐一加入 print(a)
extend是将一个数组拆散逐一加入,append将一个数组当作一个元素加入
insert
# 增:insert a=[1,2,3] a.insert(2,"jj") # 第一个表示位置,第二个表示值 print(a)
2)删除 :del remove pop
movie=['加勒比海盗',"指环王","速度与激情","指环王"] print(movie) del movie[1] #用 delete删除 print(movie) movie.remove("指环王") #删除指定内容(只删除第一个) print(movie) movie.pop() # 弹出最后一个 print(movie)
3)查:in not in
namelist2 = ["tom", "marry", "Bob",6,3,1,1] findname=input("输入查找名字:") if findname in namelist2: print("是") else: print("否")
index
a = ["a", "b", "b", "a", "b"] print(a.index("b", 0, 4)) # 查找“a”是否出现在0到4的位置上(范围左闭右开,包含0不包含4),如果是则返回第一个的具体位置 # 找不到会报错 print(a.count("b")) #查找一下“b”的数量
查找“a”是否出现在0到4的位置上(范围左闭右开,包含0不包含4),如果是则返回第一个的具体位置, 找不到会报错
3)排序 :reverse sort
#排序: a=["a","b","e","d"] a.reverse() #反转 print(a) a.sort() #升序排列 print(a) a.sort(reverse=True) #降序排列 print(a)
4、作业:
#-*- coding = utf-8 -*- #@Time :2022/1/23 16:16 #@Author :zzy #@File :demo6.py #@Software :PyCharm cars=[] flag=True price = 0 while flag == True: products = [['iphone', 6888], ['小米6', 2499], ['华为', 3499], ['魅族', 2289], ['mac', 3999], ['Vivo', 2678]] i = 0 j=-1 k=0 print("------商品列表--------") for product in products: print("%d %s %d" % (i, product[0], product[1])) i += 1 choice=input("请选择商品编号:(q表示退出结账)\n") if choice == 'q': print("------购物车列表--------") for car in cars: print("%d %s %d %d个" % (car[2], car[0], car[1], car[3])) print("总金额:%d"%price) break elif int(choice) <0 or int(choice) >=len(products): continue else: for num in cars: if "T"+choice in num: j=k k+=1 if j!=-1: price = price + products[int(choice)][1] cars[j][3]=cars[j][3]+1 else: price = price+products[int(choice)][1] products[int(choice)].append(0) products[int(choice)].append(0) products[int(choice)][3]=products[int(choice)][3]+1 products[int(choice)][2]=int(choice) cars.append(products[int(choice)]) cars[j].append("T"+choice)