五、集合
Python 中set与dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
注意,key为不可变类型,即可哈希的值。
1、集合的创建
- 先创建对象再添加元素
- 在创建空集合的时候只能使用s = set(),因为s = {}创建的是空字典。
【示例1】:
basket = set()
basket.add('apple')
basket.add('banana')
print(basket)
# {'banana', 'apple'}
- 直接把一堆元素用花括号括起来{元素1, 元素2, …, 元素n}。
- 重复元素在set中会被自动被过滤。
【示例2】:
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)
# {'banana', 'apple', 'pear', 'orange'}
- 使用set(value)工厂函数,把列表或元组转换成集合。
【示例3】:
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'}
【示例4】去掉列表中的重复元素:
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]
注:)
- 集合的两个特点:无序(unordered)和唯一(unique)
- 由于set存储的时无序集合,所以我们不可以为集合创建索引或执行切片(slice)操作,也没有键(keys)可用来获取集合中元素的值,但是可以判断一个元素是否在集合中。
2、访问集合中的值
1)使用len()内建函数得到集合的大小
【示例5】:
s = set(['Google', 'Baidu', 'Taobao'])
print(len(s))
# 3
2)用for逐个读取集合中的数据
【示例6】:
s = set(['Google', 'Baidu', 'Taobao'])
for item in s:
print(item)
# Baidu
# Google
# Taobao
3)使用in 或not in判断某个元素是否存在于集合中
【示例7】:
s = set(['Google', 'Baidu', 'Taobao'])
print('Taobao' in s) # True
print('Facebook' not in s) # True