Python 列表的創建 創建一個空列表 例如:fruit=[] 創建一個有元素的列表 例如:fruit=['apple','banana','cherry'] Python 列表元素的查找 Python 列表元素的添加和修改 Python 列表元素的刪除 Python 列表其他函數 Python ...
Python 列表的創建
創建一個空列表 例如:fruit=[]
創建一個有元素的列表 例如:fruit=['apple','banana','cherry']
Python 列表元素的查找
fruit=['apple','banana','cherry'] print(fruit) #獲取全部元素 print(fruit[:-1])#等同於上方的效果 print(fruit[:]) #等同於上方的效果 print(fruit[0]) #單個元素的獲取 print(fruit[0:3])#實際獲取0~2下標之間的元素(顧首不顧尾) print(fruit[:3]) #等同於上方的效果 print(fruit[-1]) #獲取倒數第一個元素 print(fruit[-2:-1])#只獲取倒數第二個元素 print(fruit[-2:])#從倒數第二個獲取到最後
Python 列表元素的添加和修改
fruit.append('pear') #在列表的最後添加元素 fruit.insert(1,'grape')#在下標1的位置添加元素,其他元素後移一位 fruit[0]='tomato' #元素的替換
Python 列表元素的刪除
fruit.remove('tomato') #使用名稱移除一個元素 del fruit[0] #使用下標移除元素 fruit.pop(index=0) #效果同上,預設移除最後一個 fruit.clear() #清空列表所有的元素
Python 列表其他函數
print(fruit.index('apple')) #下標的查找 print(fruit.count('apple')) #元素個數的統計 fruit.sort() #按照ascall碼排序 fruit.reverse() #反轉列表 fruit.extend([1,2,3]) #添加列表到fruit列表尾部 del fruit #刪除列表 fruit2=fruit.copy() #第一層獨立複製,第二層複製的是記憶體地址 # fruit2=fruit[:] #同上(作用可以聯合賬號) # fruit2=list(fruit) #同上 import copy fruit2=copy.deepcopy(fruit)#真正的完全複製
Python 列表的迴圈
for i in fruit:
print(i)
for i in range(len(fruit)):
print(fruit[i])
for index,data in enumerate(fruit):
print(index,data)
Python 元組的創建
創建一個空元組 例如:fruit=()
創建一個有元素的元組 例如:fruit=('apple','banana','cherry')
Python 元組的使用
元組是一個只讀列表不可用添刪改,但是可以查詢(通上方列表的查找)
Python 小試牛刀
購物車程式的書寫,思路:用戶進入界面輸入金額--->列印商品列表---->選擇商品---->扣款---->加入購入車---->退出

#coding=utf-8 #Author:gm #readme:運行程式輸入金額,進入商品列表,選擇數字購買,按q退出 commodity=[['apple','5'],['cherry','2'],['banana','1'],['grape','1']] shopping_car=[] #金額的輸入 while True: cash=input('你需要多少錢:') if cash.isdigit(): break else: print('請輸入正整數!') cash=int(cash) flag=True while cash>=0: #main #列印商品列表 for i in range(len(commodity)): print('%s. %s 價格$%s'%(i+1,commodity[i][0],commodity[i][1])) print('你的金額:$%s'%(cash)) commodity_id=input('購買:') #停止購買的條件 if commodity_id=='q': break if commodity_id.isdigit(): commodity_id = int(commodity_id) else: print('請輸入正整數!') continue if commodity_id > len(commodity) or commodity_id < 1: print('沒有件商品') continue comm_index = commodity_id-1 #主要的邏輯判斷 if int(commodity[comm_index][1]) <= cash: shopping_car.append(commodity[comm_index]) cash = cash - int(commodity[comm_index][1]) print('成功購買%s'%(commodity[comm_index][0])) else: print('對不起你的金額不足') print('------你的購物車------') for i in shopping_car: print(i) print('你的餘額$%s'%(cash))shopping_cart