Skip to content

set(集合)

与数学中的集合功能一样

集合(set)是一种无序的、可变的、不可重复的数据类型。

集合用 {} 创建,一般用作于去重

python
# 集合创建
>>> set1 = {1, 2, 2, 3, 5, 6, 4, 4}
>>> set1
{1, 2, 3, 4, 5, 6}


# 集合无需、不可重复,可以进行去重
>>> set2 = set('hello world !') 
>>> set2
{'e', 'r', 'd', 'w', 'l', 'o', 'h', ' ', '!'}

集合方法

python
>>> set1 = {1, 2}
>>> set1.add(3)    # list .append
>>> set1.add(10)
>>> set1
{10, 1, 2, 3}

>>> set1.update({'a', 'b', 'c'})   # list .extend
>>> set1
{'c', 1, 2, 3, 'b', 'a', 10}

>>> set1.remove('a')
>>> set1
{'c', 1, 2, 3, 'b', 10}

集合运算(了解)

可以进行数学中的集合运算

python
>>> set2 = {2, 3, 4}
>>> set3 = {3, 4, 5}
>>> print('交集:', set2 & set3)
交集: {3, 4}
>>> print('并集:', set2 | set3)
并集: {2, 3, 4, 5}
>>> print('差集:', set2 - set3)   # set2 比 set3 多出来的内容
差集: {2}
>>> print('异或集:', set2 ^ set3)  # 跟交集取反
异或集: {2, 5}

案例

python
a = 'hello world !'
b = 'hello python !'
  1. 在 a, b 字符串中重复的字符
  2. 在 a, b 字符串中 不重复的字符
  3. 在 a 相比 b 字符串 多出来的字符
参考答案
python
a = 'hello world !'
b = 'hello python !'

# 在 a,b 字符串中 重复的字符
print(set(a) & set(b))
# 在 a,b 字符串中 不重复的字符
print(set(a) ^ set(b))
# 在 a 相比 b 字符串 多出来的字符
print(set(a) - set(b))