在Python中,可以使用set數(shù)據(jù)結(jié)構(gòu)來表示集合,并使用內(nèi)置方法實(shí)現(xiàn)集合運(yùn)算
# 定義兩個(gè)集合
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 計(jì)算差集
difference = set1 - set2
print("Difference of set1 and set2:", difference)
# 也可以使用.difference()方法
difference2 = set1.difference(set2)
print("Difference of set1 and set2 using .difference():", difference2)
輸出:
Difference of set1 and set2: {1, 2, 3}
Difference of set1 and set2 using .difference(): {1, 2, 3}
在這個(gè)例子中,我們首先定義了兩個(gè)集合set1和set2。然后我們使用"-"運(yùn)算符和.difference()方法分別計(jì)算了這兩個(gè)集合的差集。最后,我們打印出了計(jì)算得到的差集。