1. 程式人生 > 實用技巧 >python成長之路:11/18,常用魔法總結

python成長之路:11/18,常用魔法總結

# 艹他媽的字典魔法-----------------------------------------------
# info = {"k1": 1, "k2": 2, "k3": 4, (1, 2, 3,): [1, 2, 3, 4, {"k1": 1, "k2": [1, 2]}]}
# print(info[(1, 2, 3,)][4]["k2"][1])
# dict

# 1.fromkeys()  根據序列,來建立字典,並指導統一的值
# v = info.fromkeys(["k1",123,"k3"],123)
# # print(v)

# 2 字典根據key值索引取值 info["k1"]如果key值不尊重會報錯
# print(info["k1"])

# 3.get()根據key進行取值,如果key不純在顯示None,("k1",111)不存在
# "k1"則顯示111
# info = {"k1": 1, "k2": 2, "k3": 4, (1, 2, 3,): [1, 2, 3, 4, {"k1": 1, "k2": [1, 2]}]}
# v = info.get("k1",11111)
# print(v)

# 4.pop():根據key值刪除,引數,如果key不存在顯示引數
# info = {"k1": 1, "k2": 2, "k3": 4, (1, 2, 3,): [1, 2, 3, 4, {"k1": 1, "k2": [1, 2]}]}
#
# v= info.pop('k1',99)
# print(v,info)

# 5.popitems() 不能傳引數,隨機刪除並獲取值
# info = {"k1": 1, "k2": 2, "k3": 4, (1, 2, 3,): [1, 2, 3, 4, {"k1": 1, "k2": [1, 2]}],"k6":(1)}
# v = info.popitem()
# print(v,info)

# 6. setdefault("k3",123) :設定,檢視該字典裡是否有"k3",如果key裡面有則返回"k3"對應
# 的值,如果沒有則在字典裡設定一個"k3":123
# dic = {"k1":'v1',
#        "k2":'v2'
#        }
# v=dic.setdefault("k3",123)
#
# print(dic,v)

# 7.update()更新,根據key值更新value,如果key值不存在直接在該字典裡建立新的鍵值對
# dic = {"k1":'v1',
#        "k2":'v2'
#        }
# dic.update({"k1":1111,"k2":2222,"k3":3333})
# dic.update({"k2":222})
# print(dic)

# 字典魔法常用:  key() , value() ,items() , update() , get()
# dic = {"k1":'v1',
#        "k2":'v2'
#        }
# v = dic.get("k1")
# print(v)

# 一、數字
# # int(..)
# # test = "123"
# # t = int(test)
# # print(t)
# # 二、字串
# # replace/find/jion/strip/startwith/split/upper/lower/format
# 
# # test = "i am {name},i like {like}"
# # test = test.format(name = input("請輸入名字") , like = input("請輸入一個女生的名字"))
# # print(test)
# # **表示可以加字典format
# # test = "i am {name},i like {like}"
# # v = test.format(**{"name":'alex',"like":'play girls'})
# # print(v)
# 
# # 三、列表
# # append\extend\insert
# # 索引,切片,迴圈
# # li = [1,2,3,"4",(5),[6],{"k7":7}]
# # li.insert(len(li)-1,"2個大傻逼")
# # print(li)
# # li = [1,2,3,"4",(5),[6],{"k7":7}]
# # for i in li :
# #     print(i)
# 
# # 四、元組
# # 忽略
# # 一級元素不能修改,刪除
# 
# # 五、字典
# # get\update\keys\values\items
# # for迴圈,索引
# # dic = {
# #     "k1":'v1'
# # }-+
# 
# # v = 'v1' in dic.values()
# # print(v)
# 
# # 六、布林值
# # 0 1
# # bool(..)
# # None "" {} [] () 0 --> False
# 
# # v = 0
# # s = bool(v)
# # print(s)
#enumetare(dic,1):把一個可迭代物件,組合成一個索引序列輸出