集合
Python 中set与dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
注意,key为不可变类型,即可哈希的值。
【例子】
num = {}
print(type(num)) # <class 'dict'>
num = {1, 2, 3, 4}
print(type(num)) # <class 'set'>
- 集合的创建
先创建对象再加入元素。
在创建空集合的时候只能使用s = set(),因为s = {}创建的是空字典。
【例子】
basket = set()
basket.add('apple')
basket.add('banana')
print(basket) # {'banana', 'apple'}
{‘banana’, ‘apple’}
直接把一堆元素用花括号括起来{元素1, 元素2, …, 元素n}。
重复元素在set中会被自动被过滤。
【例子】
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # {'banana', 'apple', 'pear', 'orange'}
{‘pear’, ‘orange’, ‘banana’, ‘apple’}
使用set(value)工厂函数,把列表或元组转换成集合。
【例子】
a = set('abracadabra')
print(a)
# {'r', 'b', 'd', 'c', 'a'}
b = set(("Google", "Lsgogroup", "Taobao", "Taobao"))
print(b)
# {'Taobao', 'Lsgogroup', 'Google'}
c = set(["Google", "Lsgogroup", "Taobao", "Google"])
print(c)
# {'Taobao', 'Lsgogroup', 'Google'}
{‘b’, ‘r’, ‘a’, ‘c’, ‘d’}
{‘Taobao’, ‘Google’, ‘Lsgogroup’}
{‘Taobao’, ‘Google’, ‘Lsgogroup’}
【例子】去掉列表中重复的元素
lst = [0, 1, 2, 3, 4, 5, 5, 3, 1]
temp = []
for item in lst:
if item not in temp:
temp.append(item)
print(temp) # [0, 1, 2, 3, 4, 5]
a = set(lst)
print(list(a)) # [0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5]
从结果发现集合的两个特点:无序 (unordered) 和唯一 (unique)。
由于 set 存储的是无序集合,所以我们不可以为集合创建索引或执行切片(slice)操作,也没有键(keys)可用来获取集合中元素的值,但是可以判断一个元素是否在集合中。
- 访问集合中的值
可以使用len()內建函数得到集合的大小。
【例子】
s = set(['Google', 'Baidu', 'Taobao'])
print(len(s)) # 3
可以使用for把集合中的数据一个个读取出来。
【例子】
s = set(['Google', 'Baidu', 'Taobao'])
for item in s:
print(item)
# Baidu
# Google
# Taobao
可以通过in或not in判断一个元素是否在集合中已经存在
【例子】
s = set(['Google', 'Baidu', 'Taobao'])
print('Taobao' in s) # True
print('Facebook' not in s) # True
- 集合的内置方法
set.add(elmnt)用于给集合添加元素,如果添加的元素在集合中已存在,则不执行任何操作。
【例子】
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits)
# {'orange', 'cherry', 'banana', 'apple'}
fruits.add("apple")
print(fruits)
# {'orange', 'cherry', 'banana', 'apple'}
{‘cherry’, ‘orange’, ‘banana’, ‘apple’}
{‘cherry’, ‘orange’, ‘banana’, ‘apple’}
set.update(set)用于修改当前集合,可以添加新的元素或集合到当前集合中,如果添加的元素在集合中已存在,则该元素只会出现一次,重复的会忽略。
【例子】
x = {"apple", "banana", "cherry"}
y = {"google", "baidu", "apple"}
x.update(y)
print(x)
# {'cherry', 'banana', 'apple', 'google', 'baidu'}
y.update(["lsgo", "dreamtech"])
print(y)
# {'lsgo', 'baidu', 'dreamtech', 'apple', 'google'}
{‘google’, ‘banana’, ‘cherry’, ‘apple’, ‘baidu’}
{‘apple’, ‘dreamtech’, ‘lsgo’, ‘google’, ‘baidu’}
set.remove(item) 用于移除集合中的指定元素。如果元素不存在,则会发生错误。
【例子】
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits) # {'apple', 'cherry'}
{‘cherry’, ‘apple’}
set.discard(value) 用于移除指定的集合元素。remove() 方法在移除一个不存在的元素时会发生错误,而 discard() 方法不会。
【例子】
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
print(fruits) # {'apple', 'cherry'}
{‘cherry’, ‘apple’}
- 集合的转换
【例子】
se = set(range(4))
li = list(se)
tu = tuple(se)
print(se, type(se)) # {0, 1, 2, 3} <class 'set'>
print(li, type(li)) # [0, 1, 2, 3] <class 'list'>
print(tu, type(tu)) # (0, 1, 2, 3) <class 'tuple'>
{0, 1, 2, 3} <class ‘set’>
[0, 1, 2, 3] <class ‘list’>
(0, 1, 2, 3) <class ‘tuple’>
- 不可变集合
Python 提供了不能改变元素的集合的实现版本,即不能增加或删除元素,类型名叫frozenset。需要注意的是frozenset仍然可以进行集合操作,只是不能用带有update的方法。
frozenset([iterable]) 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。
【例子】
a = frozenset(range(10)) # 生成一个新的不可变集合
print(a)
# frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
b = frozenset('lsgogroup')
print(b)
# frozenset({'g', 's', 'p', 'r', 'u', 'o', 'l'})
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
frozenset({‘l’, ‘g’, ‘r’, ‘u’, ‘o’, ‘s’, ‘p’})