原文: https://www.programiz.com/python-programming/examples/set-operation

在此示例中,我们定义了两个集合变量,并且执行了不同的集合操作:并集,交集,差和对称差。

要理解此示例,您应该了解以下 Python 编程主题:


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

源代码

  1. # Program to perform different set operations like in mathematics
  2. # define three sets
  3. E = {0, 2, 4, 6, 8};
  4. N = {1, 2, 3, 4, 5};
  5. # set union
  6. print("Union of E and N is",E | N)
  7. # set intersection
  8. print("Intersection of E and N is",E & N)
  9. # set difference
  10. print("Difference of E and N is",E - N)
  11. # set symmetric difference
  12. print("Symmetric difference of E and N is",E ^ N)

输出

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

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