標籤:epc 記憶體位址 另一個 情況 top 隨機 索引 bar 技術分享
1,集合的建立。
set1 = set({1,2,‘barry‘})set2 = {1,2,‘barry‘}print(set1,set2) # {1, 2, ‘barry‘} {1, 2, ‘barry‘}
2,集合的增。
set1 = {‘alex‘,‘wusir‘,‘ritian‘,‘egon‘,‘barry‘}set1.add(‘景女神‘)print(set1)#update:迭代著增加set1.update(‘A‘)print(set1)set1.update(‘老師‘)print(set1)set1.update([1,2,3])print(set1)
3,集合的刪。
set1 = {‘alex‘,‘wusir‘,‘ritian‘,‘egon‘,‘barry‘}set1.remove(‘alex‘) # 刪除一個元素print(set1)set1.pop() # 隨機刪除一個元素print(set1)set1.clear() # 清空集合print(set1)del set1 # 刪除集合print(set1)
4,集合的其他動作:
4.1 交集。(& 或者 intersection)
set1 = {1,2,3,4,5}set2 = {4,5,6,7,8}print(set1 & set2) # {4, 5}print(set1.intersection(set2)) # {4, 5}
4.2 並集。(| 或者 union)
set1 = {1,2,3,4,5}set2 = {4,5,6,7,8}print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7}
print(set2.union(set1)) # {1, 2, 3, 4, 5, 6, 7}
4.3 差集。(- 或者 difference)
set1 = {1,2,3,4,5}set2 = {4,5,6,7,8}print(set1 - set2) # {1, 2, 3}print(set1.difference(set2)) # {1, 2, 3}
4.4反交集。 (^ 或者 symmetric_difference)
set1 = {1,2,3,4,5}set2 = {4,5,6,7,8}print(set1 ^ set2) # {1, 2, 3, 6, 7, 8}print(set1.symmetric_difference(set2)) # {1, 2, 3, 6, 7, 8}
4.5子集與超集
set1 = {1,2,3}set2 = {1,2,3,4,5,6}print(set1 < set2)print(set1.issubset(set2)) # 這兩個相同,都是說明set1是set2子集。print(set2 > set1)print(set2.issuperset(set1)) # 這兩個相同,都是說明set2是set1超集。
5,frozenset不可變集合,讓集合變成不可變類型。
s = frozenset(‘barry‘)print(s,type(s)) # frozenset({‘a‘, ‘y‘, ‘b‘, ‘r‘}) <class ‘frozenset‘> 二,深淺copy
1,先看賦值運算。
l1 = [1,2,3,[‘barry‘,‘alex‘]]l2 = l1l1[0] = 111print(l1) # [111, 2, 3, [‘barry‘, ‘alex‘]]print(l2) # [111, 2, 3, [‘barry‘, ‘alex‘]]l1[3][0] = ‘wusir‘print(l1) # [111, 2, 3, [‘wusir‘, ‘alex‘]]print(l2) # [111, 2, 3, [‘wusir‘, ‘alex‘]]
對於賦值運算來說,l1與l2指向的是同一個記憶體位址,所以他們是完全一樣的。
2,淺拷貝copy。
l1 = [1,2,3,[‘barry‘,‘alex‘]]
l2 = l1.copy()print(l1,id(l1)) # [1, 2, 3, [‘barry‘, ‘alex‘]] 2380296895816 #可以看出,拷貝出的結果指向不同的記憶體位址,print(l2,id(l2)) # [1, 2, 3, [‘barry‘, ‘alex‘]] 2380296895048
l1[1] = 222
print(l1,id(l1)) # [1, 222, 3, [‘barry‘, ‘alex‘]] 2593038941128# 將copy 的一個內容改變,另外一個列表的值並沒有跟隨發生變化。
print(l2,id(l2)) # [1, 2, 3, [‘barry‘, ‘alex‘]] 2593038941896
l1[3][0] = ‘wusir‘print(l1,id(l1[3])) # [1, 2, 3, [‘wusir‘, ‘alex‘]] 1732315659016 #但是將內容裡邊嵌套的內容改變,另外一個copy 出來的表格也跟著改變了,
#而且通過列印他的記憶體位址可以看出,他們指向了同一個地址,
print(l2,id(l2[3])) # [1, 2, 3, [‘wusir‘, ‘alex‘]] 1732315659016 也就是嵌套的內容他們的用了同一個記憶體位址。
對於淺copy來說,第一層建立的是新的記憶體位址,而從第二層開始,指向的都是同一個記憶體位址,所以,對於第二層以及更深的層數來說,保持一致性。
3,深拷貝deepcopy。
import copyl1 = [1,2,3,[‘barry‘,‘alex‘]]l2 = copy.deepcopy(l1)print(l1,id(l1)) # [1, 2, 3, [‘barry‘, ‘alex‘]] 2915377167816print(l2,id(l2)) # [1, 2, 3, [‘barry‘, ‘alex‘]] 2915377167048l1[1] = 222print(l1,id(l1)) # [1, 222, 3, [‘barry‘, ‘alex‘]] 2915377167816print(l2,id(l2)) # [1, 2, 3, [‘barry‘, ‘alex‘]] 2915377167048l1[3][0] = ‘wusir‘print(l1,id(l1[3])) # [1, 222, 3, [‘wusir‘, ‘alex‘]] 2915377167240print(l2,id(l2[3])) # [1, 2, 3, [‘barry‘, ‘alex‘]] 2915377167304
對於深copy來說,兩個是完全獨立的,改變任意一個的任何元素(無論多少層),另一個絕對不改變。
http://www.cnblogs.com/jin-xin/articles/7738630.html
day8 python學習