# Python 集

> 原文： [https://pythonspot.com/python-set/](https://pythonspot.com/python-set/)

## 用 Python 设置

A set in Python is a collection of objects. Sets are available in Python 2.4 and newer versions. They are different from lists or tuples in that they are modeled after sets in mathematics.

## 设置示例

要创建一个集合，我们使用 set（）函数。

```py
#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
print(x)

```

如果我们多次添加相同的 item 元素，则会将其删除。 一个集合不能多次包含相同的元素。

```py
#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram", "Postcard"])
print(x)

```

## 简单记法

If you use Python version 2.6 or a later version, you can use a simplified notation:

```py
#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
print(x)

y = {"Postcard","Radio","Telegram"}
print(y)

```

## 设定方法

## Clear elements from set

To remove all elements from sets:

```py
#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.clear()
print(x)

```

## 将元素添加到集合中

要将元素添加到集合中：

```py
#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.add("Telephone")
print(x)

```

## 将元素删除到集合中

要将元素删除到集合中：

```py
!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.remove("Radio")
print(x)

```

## 两组之间的差异

要查找两组之间的差异，请使用：

```py
#!/usr/bin/env python
x = set(["Postcard", "Radio", "Telegram"])
y = set(["Radio","Television"])
print( x.difference(y) )
print( y.difference(x) )

```

请注意，x.difference（y）与 y.difference（x）不同。

## 子集

要测试集合是否为子集，请使用：

```py
#!/usr/bin/env python

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.issubset(y) )<b>
</b>

```

## 超级集

要测试集合是否是超级集，请执行以下操作：

```py
#!/usr/bin/env python

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.issuperset(y) )

```

## 交叉点

要测试交叉点，请使用：

```py
#!/usr/bin/env python

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.intersection(y) )

```