Python Set difference_update()

difference_update() 方法计算两个集合之间的差集 (A - B),并用结果集更新集合 A。

示例

# sets of numbers
A = {1, 3, 5, 7, 9}
B = {2, 3, 5, 7, 11}

# computes A - B and updates A with the resulting set A.difference_update(B)
print('A = ', A) # Output: A = {1, 9}

difference_update() 语法

difference_update() 方法的语法是

A.difference_update(B)

这里,AB 是两个集合。


difference_update() 参数

difference() 方法接受一个参数

  • B - 一个集合,其元素不会包含在结果集中

difference_update() 返回值

difference_update() 不返回任何值。


示例:Python difference_update()

A = {'a', 'c', 'g', 'd'}
B = {'c', 'f', 'g'}

print('A before (A - B) =', A)

A.difference_update(B)
print('A after (A - B) = ', A)

输出

Original Set = {'a', 'g', 'c', 'd'}
A after (A - B) =  {'a', 'd'}

在上面的示例中,我们使用了 difference_update() 方法来计算集合 AB 之间的差集,并用结果集更新集合 A

这里,A.difference_update(B) 执行 A - B 并用值 {'a', 'd'} 更新集合 A


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战