Python学习第12天:Python 集合2

139 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第16天,点击查看活动详情 >>

3、集合推导式

和列表一样,集合也支持推导式

# 判断元素是否存在
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

4、集合内置方法

4.1 difference()

difference() 方法用于返回集合的差集,即返回的集合元素包含在第一个集合中,但不包含在第二个集合(方法的参数)中,返回一个新的集合。** difference() 方法语法:**

set.difference(set)

实例: 两个集合的差集返回一个集合,元素包含在集合 x ,但不在集合 y :

# 求两个集合的差集,元素在 x 中不在 y 中
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x.difference(y)

print('两个集合的差集是:%s' % z)

# 输出结果为:
{'cherry', 'banana'}

4.2 difference_update()

  • difference_update() 方法用于移除两个集合中都存在的元素。
  • difference_update() 方法与 difference() 方法的区别在于 difference() 方法返回一个移除相同元素的新集合,而 difference_update() 方法是直接在原来的集合中移除元素,没有返回值。
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

x.difference_update(y)

print(x)
结果为:
{'banana', 'cherry'}


x1 = {1,2,3,4}
y1 = {1,2,3}

x1.difference_update(y1)

print(x1)

# 结果为:
{4}

4.3 intersection()

intersection() 方法用于返回两个或更多集合中都包含的元素,即交集,返回一个新的集合。

intersection() 方法语法:

set.intersection(set1, set2 ... etc)

**参数:**
set1 -- 必需,要查找相同元素的集合
set2 -- 可选,其他要查找相同元素的集合,可以多个,多个使用逗号 , 隔开

实例:

# 返回两个或者多个集合的交集
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}

z = x.intersection(y)

print(z)

# 返回三个集合的交集
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}

result = x.intersection(y, z)
print('三个集合的差集是:%s' % result)

# 输出结果:

{'apple'}
两个集合的差集是:{'c'}

4.4 intersection_update()

  • intersection_update() 方法用于获取两个或更多集合中都重叠的元素,即计算交集。
  • intersection_update() 方法不同于 intersection() 方法,因为 intersection() 方法是返回一个新的集合,而 intersection_update() 方法是在原始的集合上移除不重叠的元素。

intersection_update() 方法语法:

set.intersection_update(set1, set2 ... etc)

**参数**
set1 -- 必需,要查找相同元素的集合
set2 -- 可选,其他要查找相同元素的集合,可以使用多个多个,多个使用逗号‘,’ 隔开

实例:

# 返回一个无返回值的集合交集
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}

x.intersection_update(y)

print(x)

x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}

x.intersection_update(y, z)

print(x)

# 输出结果:
{'apple'}
{'c'}

4.5 union()

union() 方法返回两个集合的并集,即包含了所有集合的元素,重复的元素只会出现一次,返回值返回一个新的集合

语法:

union() 方法语法:

set.union(set1, set2...)
参数
set1 -- 必需,合并的目标集合
set2 -- 可选,其他要合并的集合,可以多个,多个使用逗号 , 隔开。

实例:

# 合并两个集合,重复元素只会出现一次:

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
 
z = x.union(y) 
 
print(z)
输出结果为:

{'cherry', 'runoob', 'google', 'banana', 'apple'}


# 合并多个集合:

实例 1
x = {"a", "b", "c"}
y = {"f", "d", "a"}
z = {"c", "d", "e"}
 
result = x.union(y, z) 
 
print(result)
输出结果为:

{'c', 'd', 'f', 'e', 'b', 'a'}