1. 程式人生 > >Python隨筆7

Python隨筆7

類型 store 就會 col 並不會 res 轉換 date() get()

字典:

字典是Python中內置的一種可變容器模型,可以把它理解為map,通過key-value的方式存儲任意類型的數據數據;創建方式為dir={"key1":value1,"key2":"value2"...}key和value之間用冒號隔開,多個ke、value之間用逗號隔開

值得註意的是字典中的鍵是唯一的,值可以不唯一

dict()方法:

dict()可以把元組或者列表轉換為字典

s1=[("Name","Tom"),("age",18)]
print("#將列表轉換為字典")
print(dict(s1))
print("#將元組轉換為字典")
s2=(["Sex","male"],["
Loc","BJ"]) print(dict(s2))

結果:

#將列表轉換為字典
{Name: Tom, age: 18}
#將元組轉換為字典
{Sex: male, Loc: BJ}

字典中的key、value的簡單查詢、增加、刪除(使用字典名[key名])

d1={"Name":"Tom","Age":20,"Hobby":"Football"}
#查找字典中已有的key
print(d1["Name"])
#向字典中增加key、value
d1["Loc"]="BJ"
print(d1)
#改變字典中的key的value
d1["Loc"]="SZ"
print
(d1)
#獲取字典中鍵值對的數量
print(len(d1))
#刪除字典中的鍵值對
del d1["Loc"]
print(d1)

結果:

Tom
{Name: Tom, Age: 20, Hobby: Football, Loc: BJ}
{Name: Tom, Age: 20, Hobby: Football, Loc: SZ}
4
{Name: Tom, Age: 20, Hobby: Football}

get()方法:

如果字典中沒有某個key,直接使用字典名[key名]的方式查詢會報錯

此時可以使用get()方法查看

d1={"Name":"Tom","Age":20,"Hobby":"Football"}
print(d1.get("Loc","key or value not defined"))
print(d1.get("Name"))

結果:

key or value not defined
Tom

clear()方法:

清除字典中所有項

x={}
y=x
print(x)
print(y)
x["Key"]="Value"
print(x)
print(y)
x.clear()
print(x)
print(y)

結果:

{}
{}
{Key: Value}
{Key: Value}
{}
{}

x、y指向同一塊內存地址,當x或者y使用了clear()方法之後,清除了字典中所有的項,那麽x、y都為空

copy()和deepcopy():

深度復制deepcopy():在內存裏面是開辟一塊新的內存,放置復制過來的數據,所以原來的對象和復制之後新創建的對象指向的是不同的內存空間,兩個對象相互獨立,不會相互影響

淺復制copy():我的理解是只要原對象和復制之後的對象數據指向同一塊內存地址,就是淺復制。對於列表來講,列表list有一個地址,列表裏面的元素各自有各自的地址,當我們對列表進行增刪改的時候,列表的地址不變,變化的是裏面的元素的地址。

例子:

這段代碼可以看出列表裏面的元素無論怎麽變化,列表的物理地址不變

x=[1,2,3,4]
print(x)
print(id(x))
x[0]=5
print(x)
print(id(x))
x.append(6)
print(x)
print(id(x))

結果:

[1, 2, 3, 4]
11628672
[5, 2, 3, 4]
11628672
[5, 2, 3, 4, 6]
11628672

例子:

下面的例子中,原字典和復制之後的字典name開始都是指向Tom的,但是無論是x或者y的name一旦發生改變,改變的那個的name就不再指向Tom但是不影響另外一個;hobby都是指向列表,這個列表無論是

增刪改都不會改變列表的物理地址,所以x、y一個改變就會影響到另外一個;字典裏新增的key-value也不會影響另外一個字典,因為另一個字典並不會指向這個新增的key-value

x={"name":"Tom","hobby":["swimming","running"]}
y=x.copy()
print(y)
y["name"]="Jerry"
print(x)
print(y)
print("--------------------------")
y["hobby"].append("drinking tea")
print(x)
print(y)
print("--------------------------")
y["hobby"].remove("running")
print(x)
print(y)
print("--------------------------")
y["loc"]="BJ"
print(x)
print(y)

結果:

{name: Tom, hobby: [swimming, running]}
{name: Tom, hobby: [swimming, running]}
{name: Jerry, hobby: [swimming, running]}
--------------------------
{name: Tom, hobby: [swimming, running, drinking tea]}
{name: Jerry, hobby: [swimming, running, drinking tea]}
--------------------------
{name: Tom, hobby: [swimming, drinking tea]}
{name: Jerry, hobby: [swimming, drinking tea]}
--------------------------
{name: Tom, hobby: [swimming, drinking tea]}
{name: Jerry, hobby: [swimming, drinking tea], loc: BJ}

理解了copy(),深度復制就比較簡單了

keys():

以列表的形式返回字典中的key

x={
    "Tom":{
        "age":12,
        "loc":"beijing"
    },
    "Jerry":{
        "age":18,
        "loc":"shanghai"
    },
    "Allen":{
        "age":20,
        "loc":"shenzheng"
    }
}
print(x.keys())

結果:

dict_keys([Tom, Jerry, Allen])

pop():

從字典中彈出指定key的項,字典會刪除這個項

x={"Name":"Tom","Age":20,"Loc":"SZ"}
print(x.pop("Loc"))
print(x)

結果:

SZ
{Name: Tom, Age: 20}

popitem():

隨機返回並刪除字典中的一對鍵值對,一般是末尾的一對

x={"Name":"Tom","Age":20,"Loc":"SZ","Hobby":"ball"}
print(x.popitem())
print(x)

結果:

(Hobby, ball)
{Name: Tom, Age: 20, Loc: SZ}

setdefaults():

def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
""" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
pass
如果鍵k在字典D中,那麽返回D["k"]對應的值,如果k不是D中的鍵,則創建一個新的鍵值對k:d
例子
x={"Name":"Tom","Age":20,"Loc":"SZ","Hobby":"ball"}
print(x.setdefault("Age"))
x.setdefault("Class","Python")
print(x)

結果:

20
{Name: Tom, Age: 20, Loc: SZ, Hobby: ball, Class: Python}

update():

x.update(y),將字典y添加到x中,x更新,y不變

x={"Name":"Tom","Age":20,"Loc":"SZ","Hobby":"ball"}
y={"Class":"Python"}
x.update(y)
print(x)
print(y)

結果:

{Name: Tom, Age: 20, Loc: SZ, Hobby: ball, Class: Python}
{Class: Python}

Python隨筆7