Update 10. 集合.md

This commit is contained in:
LSGOMYP
2020-07-21 12:40:38 +08:00
parent 61a5cba043
commit ed7b613e0f

View File

@@ -1,6 +1,7 @@
# 集合
python 中`set``dict`类似,也是一组`key`的集合,但不存储`value`。由于`key`不能重复,所以,在`set`中,没有重复的`key`
Python 中`set``dict`类似,也是一组`key`的集合,但不存储`value`。由于`key`不能重复,所以,在`set`中,没有重复的`key`
注意,`key`为不可变类型,即可哈希的值。
@@ -53,10 +54,7 @@ print(c)
# {'Taobao', 'Lsgogroup', 'Google'}
```
- 去掉列表中重复的元素
【例子】
【例子】去掉列表中重复的元素
```python
lst = [0, 1, 2, 3, 4, 5, 5, 3, 1]
@@ -84,16 +82,16 @@ print(list(a)) # [0, 1, 2, 3, 4, 5]
【例子】
```python
thisset = set(['Google', 'Baidu', 'Taobao'])
print(len(thisset)) # 3
s = set(['Google', 'Baidu', 'Taobao'])
print(len(s)) # 3
```
- 可以使用`for`把集合中的数据一个个读取出来。
【例子】
```python
thisset = set(['Google', 'Baidu', 'Taobao'])
for item in thisset:
s = set(['Google', 'Baidu', 'Taobao'])
for item in s:
print(item)
# Baidu
@@ -105,9 +103,9 @@ for item in thisset:
【例子】
```python
thisset = set(['Google', 'Baidu', 'Taobao'])
print('Taobao' in thisset) # True
print('Facebook' not in thisset) # True
s = set(['Google', 'Baidu', 'Taobao'])
print('Taobao' in s) # True
print('Facebook' not in s) # True
```
## 3. 集合的内置方法
@@ -171,9 +169,9 @@ print(x) # banana
```
由于 set 是无序和无重复元素的集合,所以两个或多个 set 可以做数学意义上的集合操作。
- `set.intersection(set1, set2 ...)` 返回两个集合的交集。
- `set.intersection(set1, set2)` 返回两个集合的交集。
- `set1 & set2` 返回两个集合的交集。
- `set.intersection_update(set1, set2 ...)` 交集,在原始的集合上移除不重叠的元素。
- `set.intersection_update(set1, set2)` 交集,在原始的集合上移除不重叠的元素。
【例子】
```python
@@ -191,7 +189,7 @@ a.intersection_update(b)
print(a) # {'a', 'c'}
```
- `set.union(set1, set2...)` 返回两个集合的并集。
- `set.union(set1, set2)` 返回两个集合的并集。
- `set1 | set2` 返回两个集合的并集。
【例子】
@@ -201,9 +199,12 @@ b = set('alacazam')
print(a) # {'r', 'a', 'c', 'b', 'd'}
print(b) # {'c', 'a', 'l', 'm', 'z'}
print(a | b) # {'l', 'd', 'm', 'b', 'a', 'r', 'z', 'c'}
print(a | b)
# {'l', 'd', 'm', 'b', 'a', 'r', 'z', 'c'}
c = a.union(b)
print(c) # {'c', 'a', 'd', 'm', 'r', 'b', 'z', 'l'}
print(c)
# {'c', 'a', 'd', 'm', 'r', 'b', 'z', 'l'}
```
- `set.difference(set)` 返回集合的差集。