日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python集合set的交集和并集操作方法_python

作者:python老鳥 ? 更新時間: 2022-05-08 編程語言

前言:

集合這種數據類型和我們數學中所學的集合很是相似,數學中堆積和的操作也有交集,并集和差集操作,python集合也是一樣。

一、交集操作

1.使用intersection()求交集

可變集合和不可變集合求交集的時候,用什么集合調用交集方法,返回的結果就是什么類型的集合。

set7 = {'name', 18, 'python2', 'abc'}
set8 = frozenset({'name', 19, 'python3', 'abc'})
res = set7.intersection(set8) ?# {'abc', 'name'} 
print(res, type(res))
res = set8.intersection(set7) ?# frozenset({'abc', 'name'}) 
print(res, type(res))

返回結果:

{'abc', 'name'}
frozenset({'abc', 'name'})

2. 使用位運算&符求交集

set5 = {'name', 18, 'python2', 'abc'}
set6 = {'name', 19, 'python3', 'abc'}
set7 = {'name', 18, 'python2', 'abc'}
set8 = frozenset({'name', 19, 'python3', 'abc'})
res = set5 & set6
print(res, type(res))
res = set7 & set8
print(res, type(res))
res = set8 & set7 ?# 誰在前,返回結果就和誰是同樣類型的集合
print(res, type(res))

返回結果:

{'abc', 'name'}
{'abc', 'name'}
frozenset({'abc', 'name'})

3.intersection_update()方法

使用此方法計算出交集之后會把結果賦值給原有的集合,屬于一種更改,所以不適用于不可變集合

set7 = {'name', 18, 'python2', 'abc'}
set8 = frozenset({'name', 19, 'python3', 'abc'})
res = set7.intersection_update(set8) ?# 沒有返回值
print(set7, type(set7)) ?# 沒有返回值,直接打印被賦值集合
res = set8.intersection_update(set7) ?# 不可變集合沒有intersection_update方法
print(res, type(res))

返回結果:

{'abc', 'name'}
AttributeError: 'frozenset' object has no attribute 'intersection_update'

4.使用intersection()方法

使用此方法求集合和其他數據類型的交集時intersection()會把其他數據類型直接轉為集合。

str1 = 'python'
list1 = [1, 2, 3, 18]
tup1 = (1, 2, 3, 18)
dict1 = {'name': 'Tom', 'age': 18, 'love': 'python'}
set10 = {'name', 18, 'python', 'abc', 'p'}
print(set10.intersection(str1)) ?
# 返回:{'p'}而不是{'python'},因為str1轉成集合為:{'y', 't', 'p', 'o', 'n', 'h'}
?
print(set10.intersection(list1))
print(set10.intersection(tup1))
print(set10.intersection(dict1))

返回結果:

{'p'}
{18}
{18}
{'name'}

二、并集操作

1.使用union()求并集

set5 = {'name', 18, 'python2', 'abc'}
set6 = {'name', 19, 'python3', 'abc'}
res = set5.union(set6)
print(res, type(res))

返回結果:

{'python2', 'abc', 18, 19, 'python3', 'name'}

2.使用邏輯或 | 求并集

set5 = {'name', 18, 'python2', 'abc'}
set6 = {'name', 19, 'python3', 'abc'}
res = set5 | set6
print(res, type(res))

返回結果:

{'abc', 'python2', 'name', 'python3', 18, 19}

3.使用update()求并集,只能作用域可變集合

set5 = {'name', 18, 'python2', 'abc'}
set6 = {'name', 19, 'python3', 'abc'}
res = set5.update(set6) ?# 有黃色波浪線表示這個函數沒有返回值
print(set5, type(set5))

返回結果:

{'python2', 'python3', 18, 'abc', 19, 'name'}

原文鏈接:https://blog.csdn.net/weixin_48728769/article/details/121718480

欄目分類
最近更新