1.创建一个空列表,命名为names,往里面添加old_driver,rain,jack,shanshan,peiqi,black_girl元素
names = ["old_driver","rain","jack","shanshan","peiqi","black_girl"] print(names)
2.往names列表里black_girl前面插入一个alex
names.insert(names.index("black_girl"),"alex") print(names)
3.把shanshan的名字改成中文,姗姗
names[names.index("shanshan")] = "姗姗" print(names)
4.往names列表里rain的后面插入一个子列表,["oldboy","oldgirl"]
names.insert(names.index("rain")+1,["oldboy","oldgirl"]) print(names)
5.返回peiqi的索引值
print(names.index("peiqi"))
6.创建新列表[1,2,3,4,2,5,6,2],合并入names列表
names.extend([1,2,3,4,2,5,6,2]) print(names)
7.取出names列表中索引4-7的元素
print(names[4:7])
8.取出names列表中索引2-10的元素,步长为2
print(names[2:10:2])
9.取出names列表中最后3个元素
print(names[-3:])
10.循环names列表,打印每个元素的索引值,和元素
#枚举 for index,name in enumerate(names): print("%s. %s" % (index,name))
#计数 index = 0 for name in names: print("%s. %s" % (index, name)) index += 1
11.循环names列表,打印每个元素的索引值,和元素,当索引值为偶数时,把对应的元素改为-1
for index,name in enumerate(names): if index % 2 == 0: names[index] = -1 print(names)
12.names里有3个2,请返回第2个2的索引值。不要人肉数,要动态找(提示,找到第一个2的位置,在次基础上再找第2个)
print(names.index(2,names.index(2)+1))
13.现有商品列表如下:
products = [ [‘iphone8‘,6888], [‘MacPro‘, 14800], [‘小米6‘,2499], [‘coffee‘,31],[‘book‘,80],[‘Nike shoes‘,799]]
请打印出这样的格式:
-----------商品信息 ------------
0. iphone8 6888
1. MacPro 14800
2. 小米6 2499
3. coffee 31
4. book 80
5. Nike shoes 799
products = [ [‘iphone8‘,6888], [‘MacPro‘, 14800], [‘小米6‘,2499], [‘coffee‘,31],[‘book‘,80],[‘Nike shoes‘,799]] print("-----------商品信息 ------------") for index,product in enumerate(products): print("%s. %s %s" % (index,product[0],product[1]))
14.利用上题中的列表,写一个循环,不断的问用户想买什么,用户选择一个商品标号,就把对应的商品添加到购物车里,最终用户输入q退出时,打印购物车里的商品列表。
products = [ [‘iphone8‘,6888], [‘MacPro‘, 14800], [‘小米6‘,2499], [‘coffee‘,31],[‘book‘,80],[‘Nike shoes‘,799]] shopping_cart = [] # 定义一个空的购物车 exit_flag = False # while True: while not exit_flag: print("-----------商品信息 ------------") for index,product in enumerate(products): print("%s. %s %s" % (index,product[0],product[1])) product_choice = input("\n请输入商品标号:\n") if product_choice.isdigit(): #判断输入的字符串是否只包含数字 product_choice = int(product_choice) # 字符串转成整型 if product_choice >= 0 and product_choice < len(products): shopping_cart.append(products[product_choice][0]) #增加到购物车列表 print("\n商品 %s 已添加到购物车\n" % (products[product_choice][0])) else: print("商品标号有误,请重新输入") elif product_choice == "q": if len(shopping_cart) > 0: print("\n您添加到购物车的商品如下:\n") for index,product_cart in enumerate(shopping_cart): print("%s. %s" % (index,product_cart)) else: print("\n您的购物车为空!\n") # break exit_flag = True #为真时候结束循环
#########################以上为列表练习题