python set
时间: 2023-07-03 10:10:52 浏览: 64
Python 的 set 是一个无序的集合,其中的元素是不可重复的。可以使用以下方式创建一个 set:
```python
my_set = {1, 2, 3}
```
也可以使用 set() 函数创建一个 set:
```python
my_set = set([1, 2, 3])
```
set 支持许多操作,例如添加元素、删除元素、求交集、求并集等。以下是一些常用的操作:
```python
my_set = {1, 2, 3}
# 添加元素
my_set.add(4)
# 删除元素
my_set.remove(3)
# 求交集
other_set = {2, 3, 4}
intersection = my_set.intersection(other_set)
# 求并集
union = my_set.union(other_set)
```
需要注意的是,set 中的元素必须是可哈希的(immutable),因此不能包含可变类型的元素,例如 list。
相关问题
python set 交集
Python中的set数据类型提供了一个方便的方法来计算两个或多个集合的交集。你可以使用`intersection`方法或`&`运算符来执行这个操作。
以下是使用`intersection`方法的示例:
```python
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
intersection_set = set1.intersection(set2)
print(intersection_set)
```
输出:
```
{4, 5}
```
以下是使用`&`运算符的示例:
```python
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
intersection_set = set1 & set2
print(intersection_set)
```
输出:
```
{4, 5}
```
以上示例中,两个集合的交集是`{4, 5}`。
pythonset函数
Python中的set()函数用于创建一个无序且不重复的集合。你可以通过将其他可迭代对象(如列表、元组和字符串)作为参数传递给set()函数来创建集合。下面是一些关于set()函数的例子:
1. 将列表转换为集合:
```python
list1 = [1, 2, 3, 4, 5]
set1 = set(list1)
print(set1) # 输出:{1, 2, 3, 4, 5}
```
2. 将元组转换为集合:
```python
tuple1 = (1, 2, 3, 4, 5)
set2 = set(tuple1)
print(set2) # 输出:{1, 2, 3, 4, 5}
```
3. 将字符串转换为集合:
```python
str1 = "Hello, world!"
set3 = set(str1)
print(set3) # 输出:{'d', 'H', 'o', ',', 'l', 'e', '!', 'r', 'w', ' '}
```
这些例子展示了如何使用set()函数将不同类型的可迭代对象转换为集合。set()函数会自动去除重复的元素,并且集合中的元素是无序的。