python中set(
时间: 2024-03-23 20:34:35 浏览: 11
在Python中,set是一种无序且不重复的集合数据类型。它可以用于存储一组元素,并且支持常见的集合操作,如交集、并集、差集等。
你可以使用大号{}或者set()函数来一个set对象。例如:
```
# 使用大括号创建set
my_set = {1, 2, 3, 4, 5}
# 使用set()函数创建set
my_set = set([1 2, 3, 4, ])
```
set中的元素是唯的,重复的元素会被自动去除。例如:
```
my_set = {1, 2, 2, 3, 3, 4, 5}
print(my_set) # 输出: {1, 2, 3, 4, 5}
```
set对象支持一系列的集合操作,例如:
- 并集:使用`union()`方法或者`|`运算符
- 交集:使用`intersection()`方法或者`&`运算符
- 差集:使用`difference()`方法或者`-`运算符
- 对称差集:使用`symmetric_difference()`方法或者`^`运算符
例如:
```
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 并集
print(set1.union(set2)) # 输出: {1, 2, 3, 4, 5}
print(set1 | set2) # 输出: {1, 2, 3, 4, 5}
# 交集
print(set1.intersection(set2)) # 输出: {3}
print(set1 & set2) # 输出: {3}
# 差集
print(set1.difference(set2)) # 输出: {1, 2}
print(set1 - set2) # 输出: {1, 2}
# 对称差集
print(set1.symmetric_difference(set2)) # 输出: {1, 2, 4, 5}
print(set1 ^ set2) # 输出: {1, 2, 4, 5}
```