Python中集合(set)的基础操作
在Python编程语言中,集合是一种无序且不重复的数据结构。它由一组唯一的元素构成,可以用来存储和处理大量数据。
创建集合:
可以使用大括号 `{}` 或 `set()` 函数来创建一个新的集合。例如:
```python
my_set = {'a', 'b', 'c'} # 使用花括号创建集合
print(my_set)
output: {'a', 'b', 'c'}
```
或者使用 `set()` 函数创建集合,如下所示:
```python
my_set = set(['a', 'b', 'c']) # 使用列表作为参数创建集合
print(my_set)
output: {'a', 'b', 'c'}
```
添加元素到集合中:
可以使用 `add()` 方法向集合中添加新元素。例如:
```python
my_set = {'a', 'b', 'c'}
my_set.add('d') # 添加一个新元素 "d"
print(my_set)
output: {'a', 'b', 'c', 'd'}
```
从集合中移除元素:
可以使用 `remove()` 方法来删除指定元素。例如:
```python
my_set = {'a', 'b', 'c'}
my_set.remove('b') # 删除元素 "b"
print(my_set)
output: {'a', 'c'}
```
注意,如果尝试移除一个不存在的元素,会引发 `KeyError`。为了避免这种情况,可以使用 `discard()` 方法来移除指定元素,它不会引发错误。例如:
```python
my_set = {'a', 'b', 'c'}
my_set.discard('d') # 尝试移除不存在的元素 "d"
print(my_set)
output: {'a', 'b', 'c'}
```
集合的并集、交集和差集:
可以使用 `union()`、`intersection()` 和 `difference()` 方法来操作两个或多个集合。例如:
```python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
tuple1 = set1.union(set2) # 求并集
print(tuple1)
output: {1, 2, 3, 4}
tuple2 = set1.intersection(set2) # 求交集
print(tuple2)
output: {2, 3}
diff_set = set1.difference(set2) # 求差集
print(diff_set)
output: {1}
```
集合的元素个数:
可以使用 `len()` 函数来获取一个集合中元素的个数。例如:
```python
my_set = {'a', 'b', 'c'}
count = len(my_set) # 获取集合中元素的个数
print(count)
output: 3
```
创建集合:
可以使用大括号 `{}` 或 `set()` 函数来创建一个新的集合。例如:
```python
my_set = {'a', 'b', 'c'} # 使用花括号创建集合
print(my_set)
output: {'a', 'b', 'c'}
```
或者使用 `set()` 函数创建集合,如下所示:
```python
my_set = set(['a', 'b', 'c']) # 使用列表作为参数创建集合
print(my_set)
output: {'a', 'b', 'c'}
```
添加元素到集合中:
可以使用 `add()` 方法向集合中添加新元素。例如:
```python
my_set = {'a', 'b', 'c'}
my_set.add('d') # 添加一个新元素 "d"
print(my_set)
output: {'a', 'b', 'c', 'd'}
```
从集合中移除元素:
可以使用 `remove()` 方法来删除指定元素。例如:
```python
my_set = {'a', 'b', 'c'}
my_set.remove('b') # 删除元素 "b"
print(my_set)
output: {'a', 'c'}
```
注意,如果尝试移除一个不存在的元素,会引发 `KeyError`。为了避免这种情况,可以使用 `discard()` 方法来移除指定元素,它不会引发错误。例如:
```python
my_set = {'a', 'b', 'c'}
my_set.discard('d') # 尝试移除不存在的元素 "d"
print(my_set)
output: {'a', 'b', 'c'}
```
集合的并集、交集和差集:
可以使用 `union()`、`intersection()` 和 `difference()` 方法来操作两个或多个集合。例如:
```python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
tuple1 = set1.union(set2) # 求并集
print(tuple1)
output: {1, 2, 3, 4}
tuple2 = set1.intersection(set2) # 求交集
print(tuple2)
output: {2, 3}
diff_set = set1.difference(set2) # 求差集
print(diff_set)
output: {1}
```
集合的元素个数:
可以使用 `len()` 函数来获取一个集合中元素的个数。例如:
```python
my_set = {'a', 'b', 'c'}
count = len(my_set) # 获取集合中元素的个数
print(count)
output: 3
```
16.9MB
文件大小:
评论区