Python 基礎-python-列表-元組-字典-集合

列表
格式:name = []
name = [name1, name2, name3, name4, name5]git


#針對列表的操做app

name.index("name1")#查詢指定數值的下標值
name.count("name1")#查詢指定數值的總數
name.clear("name")#清空列表
name.reverse("name")#反轉列表數值
name.sort("name")#排序,優先順序 特殊字符-數字-大寫字母-小寫字母
name.extend("name1")#擴展。把另外一個列表的值增長到當前列表

#增長 addiphone

name.append("name5")#追加
name.insert(1, "name1.5")#插入指定位置

#刪除 delete優化

name.remove("name1")#根據人名刪除
del name[0]#根據下標刪除列表裏的值
del name #刪除列表
name.pop(0)#刪除指定下標的值,默認是最後一個

#查詢 selectspa

print(name[0], name[2])#根據下標讀取
print(name[0:2]) == print(name[:2])#切片  (連續的一段:顧頭不顧尾,0和-1均可以省略)
print(name[-1])#-1 獲取最後一個位置的值
print(name[-2:])#獲取最後兩個值,從前日後數最後一個是-一、依次是-三、-二、-1

#更改 updatepwa

name[1] = "name1.5"#更改指定下標的值

#列表copy分爲深copy和淺copycode


深copy 會把列表裏的子列表 copy過去blog

name = ["name1", "name2", "name3", "name4", ["name5", "name6"]]
name1 = copy.deepcopy(name)
name[4][1] = "name7"
name[1] = "name2.1"
print(name)
print(name1)

result(結果)排序

['name1', 'name2.1', 'name3', 'name4', ['name5', 'name7']]
['name1', 'name2', 'name3', 'name4', ['name5', 'name6']]


淺copy 只會copy列表的第一層,若是新文件子列表裏的數值更改,老文件子列表的值不會更改ip

name = ["name1", "name2", "name3", "name4", ["name5", "name6"]]
name1 = name.copy() = copy.copy(name) = name[:] = list(name)
name[4][1] = "name7"
name[1] = "name2.1"
print(name)
print(name1)

result(結果)

['name1', 'name2.1', 'name3', 'name4', ['name5', 'name7']]
['name1', 'name2', 'name3', 'name4', ['name5', 'name7']

 元組(不可變的列表)
格式:tuple = ("tu1", "tu2")
和列表同樣,不可增刪改。只能查詢(切片)

tuple = ("tup1", "tup2")
print(tuple.count("tup1"))
print(tuple.index("tup2"))

 

練習題:

程序:購物車程序

需求:

  1. 啓動程序後,讓用戶輸入工資,而後打印商品列表
  2. 容許用戶根據商品編號購買商品
  3. 用戶選擇商品後,檢測餘額是否夠,夠就直接扣款,不夠就提醒 
  4. 可隨時退出,退出時,打印已購買商品和餘額
#購物車練習題
shoplist = [[1, "iphone", 6000], [2, "mac pro", 12000], [3, "ipad air", 8000], [4, "chicken", 30], [5, "eggs", 5], [6, "bike", 500]]
mall = []
salary = int(input("please input your salary:"))
while True:
    for i in range(0, len(shoplist)):
        print(shoplist[i])
    goodid = int(input("Please enter the number you want to buy goods:")) - 1
    if int(shoplist[goodid][2]) > salary:
        print("Don't buy goods you want")
    else:
        mall.append(shoplist[goodid])
        salary = salary - shoplist[goodid][2]
    yesorno = input("To continue shopping?input Y or N")
    if yesorno == 'N':
        print("Do you have bought the goods:%s,remaining sum:%s" % (mall, salary))
        print("Thanks for coming.")
        break

 優化修正版本:

#優化版本
import os, pickle, time

Bool = bool(True)
'''獲取已存在的用戶,如不存在 賦值爲空'''
if os.path.exists(r'user_mess.pkl') == Bool:
pkl_file = open('user_mess.pkl', 'rb')
reg_user = pickle.load(pkl_file)
pkl_file.close()
else:
reg_user = {}
'''獲取用戶的歷史購物列表'''
if os.path.exists(r'usershoplist.pkl') == Bool:
dirc = open('usershoplist.pkl', 'rb')
hist_dic = pickle.load(dirc)
dirc.close()
else:
hist_dic = {}
shopping_car = {
"iphone": {1: ["iphone", 6888, 5], 2: ["ipad", 4000, 8], 3: ["Samsung", 3000, 3]},
"variety": {1: ["headset", 50, 5], 2: ["usb_cable", 18, 8], 3: ["teacup", 60, 30]},
"clothing": {1: ["coat", 900, 5], 2: ["pants", 110, 8], 3: ["shoes", 300, 3]}
}
shop_history = {}
temporary_list = []
dict1 = {}
print("歡迎來到購物商城".center(50, '*'))
count = 0
True_False = 'True'
input_value = input("登陸輸入1,註冊輸入2,退出輸入q:")

if input_value.isdigit(): # 判斷輸入的是不是數字
if int(input_value) == 1: # 登陸流程
while True_False:
register_name = input("用戶名:")
register_pwd = input("密 碼:")
if register_name in reg_user.keys() and register_pwd == reg_user[register_name]['pwd']:
print("登陸成功".center(40, '-'))
True_False = False
else:
count += 1
if count == 3:
exit("屢次輸入錯誤,退出程序")
else:
print("******************************")
print("用戶名或者密碼錯誤!請從新輸入.")
print("******************************")
elif int(input_value) == 2: # 註冊流程
while True_False:
register_name = input("用戶名:")
register_pwd = input("密 碼:")
register_sal = input("存入金額:")
if register_name in reg_user.keys(): # 判斷用戶名是否存在,存在從新輸入,不存在註冊成功,進入商城
print("用戶已存在!從新輸入")
else:
if register_sal.isdigit():
reg_user[register_name] = {"pwd": register_pwd, "money": register_sal}
user_val = open('user_mess.pkl', 'wb')
pickle.dump(reg_user, user_val)
user_val.close()
print("註冊成功!".center(50, '-'))
True_False = False
else:
count += 1
if count == 3:
exit("屢次輸入錯誤,退出程序")
else:
print("存錢失敗!輸入正確的數字")
else:
exit("輸入錯誤!")
elif input_value == "q":
if temporary_list:
for i in temporary_list:
print(i)
else:
print("本次沒有購買任何商品哦!")
exit("謝謝您的光顧,歡迎再來")
else:
exit("Please enter the Numbers")
'''打印用戶歷史購物列表'''
if register_name in hist_dic.keys(): print("上次的購物列表") for i in hist_dic[register_name]: print(i)'''更新用戶信息'''def update_usermessage(Salary): reg_user[register_name]["money"] = Salary user_val = open('user_mess.pkl', 'wb') pickle.dump(reg_user, user_val) user_val.close()'''更新用戶已購列表'''def update_shophist(hist_list): if temporary_list: shop_history[register_name] = temporary_list file_obj = open('usershoplist.pkl', 'wb') pickle.dump(shop_history, file_obj) file_obj.close()'''充值'''def Recharge(Salary, Money): if Money.isdigit(): Salary += Money # 更新用戶金額 print("充值成功,如今餘額爲\033[31;1m [s] \033[0m" % Salary) update_usermessage(Salary) else: print("充值失敗")'''打印已購商品'''def print_list(): if temporary_list: print("已購買的商品".center(50, '=')) print("商品名 數量 金額 購買時間") for i in temporary_list: print(i) print("".center(50, '=')) else: print("本次沒有購買任何商品哦!")Salary = int(reg_user[register_name]["money"])print("購物車歡迎你 %s ,你的帳戶餘額爲%s" % (register_name, Salary))print("============================================")while not True_False: for i in enumerate(shopping_car): # 打印商品列表 print(i[0] + 1, '.', i[1]) dict1[i[0]] = i[1] print("============================================") print("(1)退出輸入 \033[31;1m q\033[0m") print("(2)充值輸入 \033[31;1m r\033[0m") print("(3)查看詳細商品輸入類型編號") select_type = input("請輸入:") if select_type == "q": # 退出並更新 用戶信息 update_usermessage(Salary) print_list() exit("歡迎下次光臨") if select_type == "r": top_up = input("輸入充值金額:") if top_up.isdigit(): Salary += int(top_up) # 更新用戶金額 print("充值成功,如今餘額爲\033[31;1m [%s] \033[0m" % Salary) update_usermessage(Salary) else: print("充值失敗") continue if select_type.isdigit(): if int(select_type) in (1, 2, 3): BIAN = int(select_type) - 1 for j in shopping_car[dict1[BIAN]]: print(j, ':', shopping_car[dict1[BIAN]][j]) print("********************************") print("(1)輸入\033[31;1m b\033[0m 返回上一層") print("(2)輸入\033[31;1m s\033[0m 查詢已購列表") print("(3)輸入\033[31;1m q\033[0m 退出") print("(4)輸入商品對應的序號,自動購買商品!") print('-------------------------------') Num = input("請輸入:") if Num == "b": continue if Num == "q": # 若是選擇退出,則判斷購物車是否爲空,不爲空就寫入到文件 print_list() update_usermessage(Salary) exit("謝謝您的光顧,歡迎再來") if Num == "s": # 選擇查詢,列表不爲空就打印,空就提示 if temporary_list: print("已購買的商品%s,餘額爲%s" % (temporary_list, Salary)) else: print("購入車空空如也!趕忙去購物吧!") elif Num.isdigit() and int(Num) <= len(shopping_car[dict1[BIAN]]) and int(Num) != 0: # 購物 shop_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) Get_num = shopping_car[dict1[BIAN]].get(int(Num))[2] # 獲取剩餘件數 Select_Digit = input("本商品一共 %s 件,你想要購買幾件:" % Get_num) # 選擇輸入幾件 if Select_Digit.isdigit() and Get_num >= int(Select_Digit): price = shopping_car[dict1[BIAN]].get(int(Num))[1] price_sum = price * int(Select_Digit) if price_sum <= int(Salary): # 判斷剩餘金額是否足夠 Salary = int(Salary) - price_sum # 更新餘額 shopping_car[dict1[BIAN]][int(Num)][2] = int(Get_num) - int(Select_Digit) temporary_list.append((shopping_car[dict1[BIAN]].get(int(Num))[0], Select_Digit, price_sum, shop_time)) # 購物信息插入列表,供查詢 print("購買成功") update_shophist(temporary_list) sel_con = input("繼續購物輸\033[31;1m c \033[0m,退出輸\033[31;1m q \033[0m," "充值按\033[31;1m r \033[0m,""查看已購列表輸 \033[31;1m s \033[0m:") if sel_con == "c": pass if sel_con == "q": update_usermessage(Salary) print_list() print("謝謝您的光顧,歡迎再來") True_False = True if sel_con == "r": top_up = input("輸入充值金額:") if top_up.isdigit(): Salary += int(top_up) # 更新用戶金額 print("充值成功,如今餘額爲\033[31;1m [%s] \033[0m" % Salary) update_usermessage(Salary) else: print("充值失敗") if sel_con == 's': print_list() else: print('-------------------------------------') print("你的餘額爲 \033[31m;%s\033[0m,餘額不足,請充值後再購買!也能夠選擇價格便宜的購買" % Salary) print('-------------------------------------') if_top_up = input("是否充值?充值輸入1,不充值按任意鍵") if if_top_up == "1": top_up = input("輸入充值金額:") if top_up.isdigit(): Salary += int(top_up) # 更新用戶金額 print("充值成功,如今餘額爲\033[31;1m [%s] \033[0m" % Salary) update_usermessage(Salary) else: print("充值失敗") else: print("請輸入正確的件數,而且最大不能超過庫存的商品件數!") else: print("請輸入正確的商品序號!") else: print("無此編號") else: print("輸入錯誤")

 

字典:(無序、無下標,根據key來查找對應的value)
格式:
info = {"key": "value",}

dictionary = {"n1": "5000",
             "n2": "5200",
             "n3": "2300",
             "n4": "9000"}
#查詢
print(dictionary["n2"])#在知道key是什麼的時候查詢,若是key不存在就報錯
print(dictionary.get("n5"))#若是key不存在會返回none,存在就返回value。
print("n2" in dictionary)#判斷key是否存在,返回true or false py2.7中格式是 dictionary.has_key("n3")
#增長
dictionary["n2"] = "5100"
dictionary["n6"] = "800"
print(dictionary)
#刪除
dictionary.pop("n7")
del dictionary["n3"]#刪除已知key對應的值,不存在會報錯
print(dictionary)
#修改
dictionary["n2"] = "5100"
dictionary["n6"] = "800"
#其餘

#values
print(dictionary.values())#查詢全部value,不輸出key
#keys
print(dictionary.keys())#只輸出key
#setdefault
dictionary.setdefault("n5", "100")#key如有就打印value,沒有就賦新value

#update(相對於兩個字典來講使用,有相同的key就替換value,無則插入)
dictionary = {"n1": "5000",
             "n2": "5200",
             "n3": "2300",
             "n4": "9000"}
dictionary1={
    "n1": "8",
    "n3": "10000",
    "n6": "100",
    "n7": "4000"
}
dictionary.update(dictionary1)
print(dictionary)
{'n2': '5200', 'n4': '9000', 'n3': '10000', 'n7': '4000', 'n1': '8', 'n6': '100'}

#items將字典轉換成列表
print(dictionary.items())
dict_items([('n2', '5200'), ('n3', '2300'), ('n4', '9000'), ('n1', '5000')])


#字典循環
方法一:

for i in dictionary:
    print(i, dictionary[i])


方法二:  會把字典dictionary轉換成列表list,不建議使用

for key, value in dictionary.items():
    print(key, value)

 #字典練習,三級菜單

# 三級菜單

menus = {"北京": {
    "東城區": {"景點": {"upward", "man"}, "大學": {"北大", "清華"}, "房山區": {"D中", "D南"}},
    "朝陽區": {"故宮": {}, "天安": {}, "東門": {}},
    "房山區": {}},
    "山東": {"煙臺": {}, "青島": {}, "濟南": {}},
    "廣州": {"東莞": {}, "廣東": {}, "佛山": {}}}

# print(menus["北京"]["朝陽"])
exit_falg = True

while exit_falg:
    for i in menus:
        print(i)
    regino = input("請輸入你要去什麼地方!1")
    if regino in menus:
        while exit_falg:
            for i1 in menus[regino]:
                print('>>>>' + i1)
            regino1 = input("請輸入你要去什麼地方!2")
            if regino1 in menus[regino]:
                while exit_falg:
                    for i2 in menus[regino][regino1]:
                        print('>>>>>>>' + i2)
                    regino2 = input("請輸入你要去什麼地方!3")
                    if regino2 in menus[regino][regino1]:
                            for i3 in menus[regino][regino1][regino2]:
                                print('>>>>>>>>>>' + i3)
                            goback = input("最後一層,按b返回上一層!")
                            if goback == "b":
                                pass
                            else:
                                exit_falg = False
                    elif regino2 == "b":
                        break
                    else:
                        exit_falg = False
            elif regino1 == "b":
                break
            else:
                exit_falg = False
    else:
        exit_falg = False

 集合 set集合 無序,不重複序列

li = [11, 22, 33, 11, 22, 33]
# 類後面加個() 就會執行類內部的一個_init_ 方法
# list(), str(), dict(), set()
# 建立集合
se = {11, 22, 33}
print(type(se))

s = set() # 建立一個空的集合
s3 = set(li) # 轉換出一個集合
print(s3) # {33, 11, 22}

# 操做集合
s = set()
s.add(123)
print(s)
s.clear()
print(s)

s1 = {11, 22, 33}
s2 = {22, 33, 44}

s3 = s1.difference(s2)   # A中存在,B中不存在
print(s3)   # 11
s4 = s1.symmetric_difference(s2)    # A中存在,B中不存在的值和 B中存在,A中不存在的值
print(s4)   # {11, 44}

s1.difference_update(s2)   # A中存在,B中不存在的值更新到新的集合中
print(s1)   # {11}
s2.symmetric_difference_update(s1)     # 差集更新到s2
s3 = s1.intersection(s2)    # 交集
s1.intersection_update(s2)  # 交集更新到s1
s5 = s1.union(s2)   # 並集
print(s5)
print(s2)   # {11, 44}
s1.discard(2222)    # 移除指定元素,不存在不報錯
s1.remove(222)  # 移除指定元素, 不存在報錯
new = s1.pop()    # 無參數,隨機移除,並返回移除的值
lis = [1, 3, 4, 6, 6]
s1.update(lis)     # 迭代更新,至關於屢次添加
print(s1)
 
# 練習題
old_dict = {
    "1": 8,
    "2": 4,
    "4": 2
}
new_dict = {
    "1": 4,
    "2": 4,
    "3": 2
}

old_set = set(old_dict.keys())
new_set = set(new_dict.keys())

remove_set = old_set.difference(new_dict)   # 應該刪除的
add_set = new_set.difference(old_set)   # 應該增長的
update_set = new_set.intersection(old_set)  # 應該更新的

print(remove_set,add_set,update_set)

for i in remove_set:
    old_dict.pop(i)
    # del old_dict[i]

print(old_dict['2'])
print(new_set)
for i in add_set:
    old_dict[i] = new_dict[i]

for i in update_set:
    old_dict[i] = new_dict[i]

print(old_dict)
相關文章
相關標籤/搜索