python的集合操作

2021-09-20 13:17:34 字數 546 閱讀 8912

集合常用於去重和求交集和並集,例項**如下:

#集合操作

pro_set = set()

for i in 'programming':

pro_set.add(i)

print(pro_set)

py_set = set()

for i in 'python':

py_set.add(i)

print(py_set)

#並集uni_set = pro_set | py_set

print(uni_set)

#交集diff_set = pro_set & py_set

print(diff_set)

#差集print(pro_set - py_set)

#對稱差

print(pro_set ^ py_set)

非常快捷和便於記憶的方式是使用|,&,-,^來代替使用.difference(),.union()這類的方法,同時也非常的形象。

兩個集合的對稱集和交集組成兩個集合的並集。

python 的集合操作

s print s dic 集合與字典不同的是,字典是鍵值對組成的 print dic a 集合是不同的元素組成 注意可以去除重合的 print a i 集合的無序性和不可重性 print i l 集合的不可變性 可以定義元組不能定義列表 print l o set hello 自帶的內建函式 可以...

python集合的操作

集合的操作 lb1 1 4,5 8,3 6,4 9,10 11,18 12,13 114,15 11,17 19,25 20,24 23,22 設定變數列表1 lb1 set lb1 轉換為集合 print lb1,type lb1 列印lb1資料,檢視lb1資料型別 lb2 2 3,5 7,9 1...

python集合操作

集合操作建立列表的兩種方式 第一種方式 建立列表 list set 4,6,5,7,13,23,45 第二種方式 list 1 1,3,2,5,7,9,17 list 1 set list 1 list 2 set 4,6,5,7,13,23,45 print list 1,list 2 1 取交集...