From ed7b613e0ffd5555c3a9cac9d5c11df859efb698 Mon Sep 17 00:00:00 2001 From: LSGOMYP Date: Tue, 21 Jul 2020 12:40:38 +0800 Subject: [PATCH] =?UTF-8?q?Update=2010.=20=E9=9B=86=E5=90=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Python-Language/10. 集合.md | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/Python-Language/10. 集合.md b/Python-Language/10. 集合.md index 7b1969d..c860cb9 100644 --- a/Python-Language/10. 集合.md +++ b/Python-Language/10. 集合.md @@ -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)` 返回集合的差集。