文章目錄
- dict
- set
- 4.用集合為列表去重
- 5.集合的增 add,update
- 6.集合的刪 discard,remove,pop,clear
- 7 集合運算
- 7.1 子集(<或者issubset()方法)
- 7.2并集(|或者union()方法)
- 7.3 交集(&或者intersection())
- 7.4 差集(-或者difference()方法)
- 7.5 對稱集(^或者symmetric_difference())
- 8.集合的copy(淺復制)
dict
Python內置了字典:dict的支持,dict全稱dictionary,在其他語言中也稱為map,使用鍵-值(key-value)存儲,具有極快的查找速度。
d = {‘Michael’: 95, ‘Bob’: 75, ‘Tracy’: 85}
下面使一些常用的方法:
def clear(self): # real signature unknown; restored from __doc__""" D.clear() -> None. Remove all items from D. """passdef copy(self): # real signature unknown; restored from __doc__""" D.copy() -> a shallow copy of D """pass@staticmethod # known case
def fromkeys(*args, **kwargs): # real signature unknown""" Create a new dictionary with keys from iterable and values set to value. """passdef get(self, *args, **kwargs): # real signature unknown""" Return the value for key if key is in the dictionary, else default. """passdef items(self): # real signature unknown; restored from __doc__""" D.items() -> a set-like object providing a view on D's items """passdef keys(self): # real signature unknown; restored from __doc__""" D.keys() -> a set-like object providing a view on D's keys """passdef pop(self, k, d=None): # real signature unknown; restored from __doc__"""D.pop(k[,d]) -> v, remove specified key and return the corresponding value.If key is not found, d is returned if given, otherwise KeyError is raised"""passdef popitem(self, *args, **kwargs): # real signature unknown"""Remove and return a (key, value) pair as a 2-tuple.Pairs are returned in LIFO (last-in, first-out) order.Raises KeyError if the dict is empty."""passdef setdefault(self, *args, **kwargs): # real signature unknown"""Insert key with a value of default if key is not in the dictionary.Return the value for key if key is in the dictionary, else default."""passdef update(self, E=None, **F): # known special case of dict.update"""D.update([E, ]**F) -> None. Update D from dict/iterable E and F.If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = vIn either case, this is followed by: for k in F: D[k] = F[k]"""passdef values(self): # real signature unknown; restored from __doc__""" D.values() -> an object providing a view on D's values """pass
-
dict的key必須是不可變對象
這是因為dict根據key來計算value的存儲位置,如果每次計算相同的key得出的結果不同,那dict內部就完全混亂了。這個通過key計算位置的算法稱為哈希算法(Hash)。
要保證hash的正確性,作為key的對象就不能變。在Python中,字符串、整數等都是不可變的,因此,可以放心地作為key。而list是可變的,就不能作為key。
set
set和dict類似,也是一組key的集合,但不存儲value。由于key不能重復,所以,在set中,沒有重復的key。
- 集合是一個無序可變不重復元素的序列(由于集合是無序的,所以不支持索引) , 集合的元素不能為可變類型(列表、字典、集合)
- 創建方式
可以使用 { } 或 set( ) 創建集合,但是創建一個空集合時,只能使用set( ) - 集合的特點:
-
無序性:集合中每個元素的地位是相同的,元素之間是無序的
-
互異性:一個集合中,每個元素只能出現一次,任何元素之間都是不相同的
-
確定性:給定一個集合,給定一個元素,該元素或屬于該集合,或不屬于該集合
4.用集合為列表去重
>>> list_1 = [1,4,6,8,1,4,6,8]
>>> list_1
[1, 4, 6, 8, 1, 4, 6, 8]
>>> set_1 = set(list_1)
>>> set_1
{8, 1, 4, 6}
>>> list_2=list(set_1)
>>> list_2
[8, 1, 4, 6]
5.集合的增 add,update
集合本省是可變的,所有可以增,刪
增的方法有:
- add :增加單個元素
- update:增加多個元素,還可以使用其他,列表,元組,字符串或者其他集合作為參數
例子:
>>> k = {'x','y'}
>>> k.add('r')
>>> k.add('v','f')
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: add() takes exactly one argument (2 given)
>>> k.update('v','f')
>>> k
{'f', 'x', 'v', 'r', 'y'}
從最后輸出的值,我們發現,集合本身存儲是沒有順序的。
6.集合的刪 discard,remove,pop,clear
可以使用discard()和remove()方法刪除集合中特定的元素
兩者區別:如果集合中不存在指定元素,使用discard()保持不變,但是在這種情況下,remove()會引發KeyError.
>>> k
{'f', 'x', 'v', 'r', 'y'}
>>> k.discard('z')
>>> k.remove('z')
Traceback (most recent call last):File "<stdin>", line 1, in <module>
KeyError: 'z'
>>> k.remove('x')
>>> k
{'f', 'v', 'r', 'y'}
>>> k.discard('y')
>>> k
{'f', 'v', 'r'}
此外還可以使用pop()方法返回并刪除一個隨機元素
>>> k
{'f', 'v', 'r'}
>>> k.pop()
'f'
>>> k
{'v', 'r'}
>>> k.clear()
>>> k
set()
- 由于集合和無序的,會隨機pop某個元素。
7 集合運算
運算符 | 描述 |
---|---|
s &= z | 把s更新為s和z的交集 |
s | =z | 把s更新為s和z的并集 |
s -= z | 把s更新為s和z的差集 |
s ^= z | 把s更新為s和z的對稱差集 |
7.1 子集(<或者issubset()方法)
>>> A = set('hello')
>>> B = set('world')
>>> A
{'l', 'h', 'o', 'e'}
>>> B
{'o', 'l', 'w', 'r', 'd'}
>>> c= set('he')
>>> c < A
True
>>> c <B
False
>>> c.issubset(A)
True
7.2并集(|或者union()方法)
>>> A= {'hello','world'}
>>> B= {'hello','beijing'}
>>> C= {'HELLO','Sh'}
>>> A|B
{'world', 'hello', 'beijing'}
>>> A.union(C)
{'world', 'hello', 'HELLO', 'Sh'}
7.3 交集(&或者intersection())
>>> A= {'hello','world'}
>>> B= {'hello','beijing'}
>>> C= {'HELLO','Sh'}
>>> A&B
{'hello'}
>>> A.intersection(B)
{'hello'}
>>>
7.4 差集(-或者difference()方法)
A-B的差集是所有屬于A且 不屬于B的元素構成的集合
>>> A= {'hello','world'}
>>> B= {'hello','beijing'}
>>> C= {'HELLO','Sh'}
>>> A-B
{'world'}
>>> A.difference(B)
{'world'}
>>> A-C
{'world', 'hello'}
7.5 對稱集(^或者symmetric_difference())
兩個集合的對稱集是只屬于其中一個集合,而不屬于另外一個集合的元素組成的集合
>>> A= {'hello','world'}
>>> B= {'hello','beijing'}
>>> C= {'HELLO','Sh'}
>>> A ^B
{'beijing', 'world'}
>>> A.symmetric_difference(B)
{'beijing', 'world'}
>>> A.symmetric_difference(C)
{'world', 'hello', 'HELLO', 'Sh'}
可以理解為把兩個集合進行了去重,然后組合成一個新的集合。
8.集合的copy(淺復制)
s = {'hello','world','beijing',frozenset('kkf')}
print(s)
s2=s.copy()
print(s2)
結果如下:
從運行結果來看,這里的copy是淺拷貝。