1. 程式人生 > >python中的dict與set以及可變物件

python中的dict與set以及可變物件

1.dict與c++中的map操作基本是一樣的(目前看來),主要是鍵值的對映關係操作操作方法如下:

dict_test = {'a': 1, 'b': 2, 'c': 3}
print(dict_test['a'])       #output 1
print('z' in dict_test)     #output false
print(dict_test.get('z'))   #output None

上面分別是建立對映,輸出對映值,判斷是否有'z'這個鍵,直接用get方法輸出若存在這個鍵值關係會直接輸出沒有就輸出none

dict是一種犧牲空間換取時間的方法,高效的搜尋,同時它的鍵是不可變物件,python中str和整形是不可變物件(list是可變物件,因此若用list當作鍵是不行的)

2.set與c++中的set操作基本是一樣的(目前看來),在搞acm時經常用set來處理一些資料,c++中set的特性是會自動從小到大排列將值,同時會去掉重複的值,且是沒有鍵的直接處理值的,想要遍歷需要迭代器;在python當中是有很大區別的,【注意】:要建立一個set需要list當作輸入集合,它會去掉集合中的重複的,但是並不會對集合中的元素進行從小到的排序,具體操作如下:

dict_test = set(['a', 'b', 'h', 'c', 'd', 'a', 'c'])
print(dict_test)         #output {'d', 'a', 'b', 'c', 'h'}
dict_test.add('f')
print(dict_test)         #output {'d', 'a', 'b', 'f', 'c', 'h'}
dict_test.remove('b')
print(dict_test)         #output {'d', 'a', 'f', 'c', 'h'}

同時set還是可以當作集合交集和並集操作的,如下程式碼:

dict_test = set(['a', 'b', 'h', 'c', 'd', 'a', 'c'])
print(dict_test)                    #dict_test output {'d', 'a', 'b', 'c', 'h'}
dict_test1 = dict_test
dict_test1.add('f')
print(dict_test | dict_test1)       #dict_test | dict_test1 output {'a', 'b', 'f', 'd', 'c', 'h'}
print(dict_test1)                   #dict_test1  output {'f', 'a', 'b', 'd', 'c', 'h'}
dict_test2 = dict_test
dict_test2.remove('b')
print(dict_test2)                   #dict_test2 output {'f', 'a', 'd', 'c', 'h'}
print(dict_test1 & dict_test2)      #dict_test1 & dict_test2 output {'a', 'f', 'd', 'c', 'h'}

之前說了python中str也就是字串屬於不可變型別,下面舉個例子,見程式碼:

str_test = 'abc';
str_test1 = str_test.replace('a', 'd')
print(str_test)             #str_test output abc
print(str_test1)            #str_test1 output dbc

也就是說不可變物件是可以當作鍵的,就像c++中 map<string, int>一樣的道理

/*以上純屬學習筆記,有誤請你指出,非常感謝,我們一同進步*/