1、认识集合 set
1.1 含义
Python中的集合是一个无序的、不包含重复元素的数据结构。集合主要用于数学上的集合操作,如并集、交集、差集和对称差集等
1.2 格式
# 语法格式
变量 = {元素1, 元素2, 元素3, ...}# 示例1
data = {1, 2, 3}
print(data, type(data)# 示例2
data = {}
print(data, type(data)) # {}# 示例3 # 定义空集合 data = set() print(data, type(data))
1.3 特点
(1)无序 ==> 没有下标 ==》 不可切片
集合中的元素没有固定的排列顺序
# 示例1
s = {"a", "b", "c"}
print(s)# 示例2
s = {1, 2, 3, 99, 88, 999}
print(s)(2)唯一 ==> 自动去重
集合中不允许有重复的元素
# 示例
s = {1, 2, 3, 2, 1}
print(s)(3)元素可哈希性
集合中的元素/字典中的键 必须是可哈希的!
# 示例1
s = {1, 2}
dic = {1: 1}
print(s, dic)# 示例2
print(hash("xiaobai"))# 示例3
dic = {"a": 1}
s = {"xiaobai"}
print(hash([1, 2, 3])) # TypeError: unhashable type: 'list'
s = {[1, 2]} # TypeError: unhashable type: 'list'
s = {[1, 2]: 1} # TypeError: unhashable type: 'list
print(hash((1, 2, 3))
print(hash({"A": 1})) # TypeError: unhashable type: 'dict
print(hash({1, 2, 3})) # TypeError: unhashable type: 'set'无序且唯一;无下标,无键名;无法查询元素、修改元素
著作权归文章作者所有。 未经作者允许禁止转载!