用于演示不同集合操作的 Python 程序

要理解这个例子,你应该具备以下 Python 编程 主题的知识


Python 提供了一种称为集合的数据类型,其元素必须是唯一的。它可用于执行不同的集合操作,如并集、交集、差集和对称差集。

源代码

# Program to perform different set operations like in mathematics

# define three sets
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};

# set union
print("Union of E and N is",E | N)

# set intersection
print("Intersection of E and N is",E & N)

# set difference
print("Difference of E and N is",E - N)

# set symmetric difference
print("Symmetric difference of E and N is",E ^ N)

输出

Union of E and N is {0, 1, 2, 3, 4, 5, 6, 8}
Intersection of E and N is {2, 4}
Difference of E and N is {8, 0, 6}
Symmetric difference of E and N is {0, 1, 3, 5, 6, 8}

在这个程序中,我们取两个不同的集合,并对它们执行不同的集合操作。这也可以通过使用集合方法来完成。

要了解更多信息,请访问 Python 集合方法

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

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

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

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