python中set函数
时间: 2023-08-21 14:23:55 浏览: 97
set() 是 Python 内置函数之一,用于创建一个无序不重复元素的集合。可以将一个列表、元组或字符串转换为集合。例如:
```python
my_list = [1, 2, 3, 3, 4, 5, 5]
my_set = set(my_list)
print(my_set) # 输出 {1, 2, 3, 4, 5}
```
除了创建集合,set() 还可以用于对两个集合进行操作,例如求交集、并集、差集等。例如:
```python
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
intersection = set1.intersection(set2) # 求交集
print(intersection) # 输出 {4, 5}
union = set1.union(set2) # 求并集
print(union) # 输出 {1, 2, 3, 4, 5, 6, 7, 8}
difference = set1.difference(set2) # 求差集
print(difference) # 输出 {1, 2, 3}
```
以上是 set() 的基本用法,还有一些其他的方法可以对集合进行操作,具体可以查看 Python 官方文档。
阅读全文
相关推荐
















