標籤:amp opp 類型 增加 choice iphone 枚舉 整型 --
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 = 0for name in names: print("%s. %s" % (index, name)) index += 111.迴圈names列表,列印每個元素的索引值,和元素,當索引值為偶數時,把對應的元素改為-1
for index,name in enumerate(names): if index % 2 == 0: names[index] = -1print(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 #為真時候結束迴圈
#########################以上為列表練習題
第2章 Python資料類型 練習題&作業