python零基礎入門day2--列表與字典
如果我們想要儲存一堆具有相同性質的資料的時候應該怎麼做?比如說現在我想用python儲存一個班裡所有同學的資訊,我該怎麼儲存?難道要一個一個建立變數來儲存嗎?這樣實在是太笨了,如果我想要儲存整個學校同學的名單,那還不得累死。python中有這麼些資料結構,可以幫助我們解決儲存大量資料的問題。
列表
列表是一種儲存變數的資料結構,宣告一個列表的方法如下:
numbers = ['1', '2', '3']
建立了一個儲存數字123字串的列表。 列表用中括號括起,列表中的元素以逗號隔開。理論上來說,只要你的記憶體夠大,列表的儲存上限是不存在的。這也是python中一個便利的地方,它不會像c++、java中的陣列一樣在定義時就要求指定大小,並且不需要指定列表中的資料型別,我們想在列表裡邊存什麼就存什麼。
列表的遍歷 列表的遍歷也十分簡單,用for迴圈就夠了:
for number in numbers:
print(number)
上面的程式碼使列表numbers中的元素依次輸出 列表的增刪查改 增加: 要往列表中增加元素只需要呼叫列表中的append函式就夠了:
list.append(element)
上邊的程式碼使element加入到列表的末尾 查詢: 可以通過索引來訪問列表中的元素,比如說我要獲得list中的第一位元素:
list[0]
就獲得了列表中的第一位元素。 修改: 如果想要修改列表中的值直接對其賦值就好:
list[0] = "1"
上邊的程式碼把列表中的第一位元素改成了字串1。
刪除: 刪除python中任何的元素最簡單粗暴的方法就是del,要刪除列表中的第一位元素,可以用下面的程式碼:
del list[0]
還可以使用remove函式,具體使用方法如下:
list.remove(object)
刪除列表中第一個出現的object pop函式可以按索引刪除列表中的元素:
list.pop(0)
刪除了列表中的第一個元素。
列表的切片 如果我們只需要用到列表中的一部分元素而不需要其他的元素,可以使用列表的切片。 比如說假設students列表中儲存了全班同學的排名資訊,而我只想要獲得前三名同學的資訊,我們可以這樣:
print(students[:3])
這段程式碼輸出了students中前三位的元素。 在冒號的兩端分別是切片的開始位置和結束位置,空著表示開頭(結尾),切片的結果不包括冒號後邊的位置。需要注意的是,列表的索引是從0位置開始的,而不是我們通常所理解的1開始。比如上例中我們從0位置(開頭)開始,一直截到3位置之前(不包括3位置),得到的是原列表0、1、2號位的共計三個元素。
列表常用的函式: len() len函式接收一個列表,返回該列表的長度:
len(list)
index() index函式接受一個物件,返回該物件第一次在列表中出現的位置,如果列表中不存在該物件則會丟擲一個ValueError異常。
index = list.index(object)
元組
元組與列表基本一樣,只不過元組一旦確定就無法修改了,其定義方式如下:
tuple = ("1", "2", "3")
無法修改元組中的元素:
tuple[0] = '4'
這樣操作時,直譯器會報錯:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
字典
字典是python的一種資料結構,這種資料結構中的每一個元素都是一個鍵值對,比如說一個學生的資訊可以這樣表示:
學號:[姓名,年齡,性別,班級,成績]
這樣學號就是鍵值對中的鍵,與這個學生相關的資訊就是鍵值對中的值。 接下來看python中字典如何定義:
dict = {key1: value1, key2: value2}
修改 update()兩個字典的“並” items()將字典轉成列表 dict.fromkeys()初始化一個字典 新增 查詢print(info.get(key)) key in info 刪除del,pop(),popitem()
迴圈 for i in info: print(i, info[i])
for k, v in info.items(): print(k, v)
購物車程式
isdigit()函式判斷輸入是否是數字 enumerate()函式 \033[31;1m%s\033[0m
字串常用操作
capitalize()開頭字母大寫 count()計運算元串數量 center()將字串格式化居中 endswith()判斷字串是否以某個字元結尾 split()按某個字元分割 join()將列表中的字串按某種方式合併 expendtabs()將縮排變成指定的大小 find()查詢子串所在的位置 format()格式化字串 format_map()格式化字串,引數為一個字典 isalnum()判斷字串是否僅由阿拉伯數字組成 isdigit()# 判斷是否為數字 isdecimal()判斷是否為十進位制 isidentifier()# 判斷是不是一個合法的識別符號 islower()判斷是不是小寫 isupper()判斷是不是大寫 isnumeric()判斷是不是數字 title()將字串中每個首字母大寫 isprintable()tty檔案,判斷是否可以列印 ljust()將字串左對齊並使用所給字串填充 rjust()將字串右對齊並用所給字串填充 lower()將字串中字母變為小寫 upper()將字串中字母變成大寫 lstrip()去除字串左邊的空格 rstrip()去除字串右邊的空格 strip()去除字串中的空格 replace()將字串中的子串用給定字元替換 splitlines()按換行符分割 swapcase()更換大小寫
作業
購物車優化: import json
程式:購物車程式
需求:
啟動程式後,讓使用者輸入工資,然後列印商品列表
允許使用者根據商品編號購買商品
使用者選擇商品後,檢測餘額是否夠,夠就直接扣款,不夠就提醒
可隨時退出,退出時,列印已購買商品和餘額
使用者入口:
1.商品資訊,餘額存在檔案裡
2.已購物品
商家入口:
1.可以新增物品、刪除物品、修改商品價格
商品列表
try: with open(“product_list.json”) as file_object: product_list = json.load(file_object) except json.decoder.JSONDecodeError: product_list = [ (“iphone”, 5800), (“car”, 300000), (“coffee”, 33), (“Mac”, 12000), (“iwatch”, 10600), (“book”, 78) ]
輸入使用者名稱
username = input(“username:”)
使用者入口
if username == “customer”: try: with open(“goods.json”) as file_object: fill_list = json.load(file_object) except json.decoder.JSONDecodeError: # 購物車清單 shopping_list = [] # 輸入工資 salary = int(input(“您的工資:”)) else: shopping_list = fill_list[0] salary = fill_list[1] print(“您的餘額為:%d” % salary)
# 輸出商品列表
for index, product in enumerate(product_list):
print(index, product)
while True:
user_choice = input("請選擇你要購買的商品編號:")
# 判斷是否是數字
if user_choice.isdigit():
number = int(user_choice)
if 0 <= number < len(product_list):
# 判斷夠不夠錢
if product_list[number][1] <= salary:
shopping_list.append(product_list[number])
salary = salary - product_list[number][1]
print("%d號商品已經加入您的購物車中 您的餘額:\033[31;1m%d\033[0m" % (number,
salary))
else:
print("你的錢不夠了")
else:
print("沒有", number, "號商品!")
elif user_choice == "q":
print("退出")
break
else:
print("請輸入正確的指令!")
for good in shopping_list:
print(good)
print("您的餘額為:", salary)
# 儲存在一個列表裡
fill_list = [shopping_list, salary]
with open("goods.json", "w") as file_object:
json.dump(fill_list, file_object)
商家入口
elif username == “admin”: # 輸出商品列表 for index, product in enumerate(product_list): print(index, product) print(“1.增加商品”) print(“2.刪除商品”) while True: choice = input(“請選擇要執行的操作:”) if choice == “1”: while True: choice = input(“請輸入商品名:”) if choice == “q”: break price = int(input(“請輸入商品價格:”)) product_list.append((choice, price)) elif choice == “2”: for index, good in enumerate(product_list): print(good) while True: choice = input(“請輸入要刪除的商品:”) if choice.isdigit(): choice = int(choice) if 0 <= choice < len(product_list): del product_list[choice] else: print(“請輸入正確的數字!”) elif choice == “q”: break else: print(“請輸入正確的指令!”) continue elif choice == “q”: break else: print(“請輸入正確的指令!”) continue for name in product_list: print(name) with open(“product_list.json”, “w”) as file_object: json.dump(product_list, file_object)