一、列表操作
a) 循环
基本语法 for i in value :
L1 =[‘a‘,‘b‘,‘c‘,‘d‘,1,2,3,4,5,6,‘b‘,‘D‘] for i in L1: print(i)
range 函数 创建列表
for i in range(5,10): print(i)
b)排序 sort()
不能对包含str及int的列表进行排序
排序的规则是按照 ASCII编码的编号进行排序
反向排序 reverse()
列表的其他用法
extend() 函数 将一个列表扩展到另外一个列表
利用 + 号也可以实现一样的拼接功能
clear() 清空列表
二、列表练习题
#1 names = [‘jiu‘,‘lin‘,‘liang‘,‘kun‘,‘ting‘] #2 names.insert(0,"small") #3 names[0] = "九" #4 names.append([‘good‘,‘like‘]) #5 print(names.index("kun")) #6 names_1 = [1,2,3,4,5,6,2] names = names + names_1 #7 print(names[4:7]) #8 print(names[2:10:2]) #9 print(names[-3:]) #10 #enumerate 的意思是枚举,获取元素的索引值 for index,l in enumerate(names): print(index,l)
#11for index,l in enumerate(names): if index %2 == 0: names[index] = -1print(names)#12names = [‘jiu‘,‘lin‘,‘liang‘,2,‘kun‘,2,‘ting‘]a = names.index(2)names_1 = names[a+1:]b = names_1.index(2)print("2的索引位置为",a+b+1)
#14 购物车
products = [["iphone8","6888"],["MacPro","14800"],["小米6","2488"],["Book","80"],["Niike","888"]] leng = len(products) run = True shop_list = [] while run: print("-------商品列表------") for index,l in enumerate(products): print ("%s %s %s" %(index,l[0],l[1])) user_1 = input("请输入你购买的商品序号》》:") if user_1.isdigit(): user_1 = int(user_1) if user_1 >= 0 and user_1 < leng: shop_list.append(products[user_1]) print("你购买了",products[user_1]) else: print("请输入正确商品序号") elif user_1 == "q": if len(shop_list) == 0: print("你的购物车是空的") else: print("--------购物车---------") for index,l in enumerate(shop_list): print (index,l[0],l[1]) run = False
注意事项代码最好别截图;路径和文件避免用中文名。
原文地址:https://www.cnblogs.com/mjiu/p/8511828.html
时间: 2024-11-07 11:21:17