元组
Python 的元组(tuple,简写为tup)与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号()
,列表使用方括号[]
。
好处就是节省内存。
集合
-
集合是无序、不重复元素的容器。
-
用
{}
或set()
创建,但空集合必须用set()
({}
会创建空字典)。 -
元素必须是不可变类型(如数字、字符串、元组),不能是列表或字典。
s1 = {1, 2, 3} # 直接定义集合
print("s1",s1)
s2 = set([1, 2, 3, 2]) # 从列表转集合(自动去重):{1, 2, 3}
print("s2",s2)
s3 = set("hello") # 从字符串转集合:{'h', 'e', 'l', 'o'}
print("s3",s3)
empty_set = set() # 空集合(注意:不是 {},那是字典)
print("empty_set",empty_set)
s1 {1, 2, 3}
s2 {1, 2, 3}
s3 {'l', 'o', 'e', 'h'}
empty_set set()
添加删除元素
#添加元素
s = {1, 2}
s.add(3) # 添加单个元素 → {1, 2, 3}
s.update([4, 5]) # 添加多个元素 → {1, 2, 3, 4, 5}
print("s",s)
#删除元素
s.remove(3) # 删除元素(元素不存在则报错 KeyError)
print("s 删除元素",s)
s.discard(6) # 删除元素(元素不存在不报错)
print("s 删除不存在元素",s)
s.pop() # 随机删除并返回一个元素(集合无序)
print("s 随机删除元素",s)
s.clear() # 清空集合 → set()
print("s 清空",s)
s {1, 2, 3, 4, 5}
s 删除元素 {1, 2, 4, 5}
s 删除不存在元素 {1, 2, 4, 5}
s 随机删除元素 {2, 4, 5}
s 清空 set()
集合运算
a = set('abracadabra')
b = set('alacazam')print("a",a)
print("b",b)print("a集合中b没有的元素",a-b)
print("并集:",a|b)
print("交集",a&b)
print("不同时包含于a和b的元素",a^b)
a {'a', 'b', 'c', 'd', 'r'}
b {'a', 'm', 'z', 'c', 'l'}
a集合中b没有的元素 {'d', 'b', 'r'}
并集: {'a', 'm', 'b', 'z', 'c', 'd', 'l', 'r'}
交集 {'a', 'c'}
不同时包含于a和b的元素 {'d', 'l', 'r', 'm', 'b', 'z'}
其他方法
#成员检测
s = {1, 2, 3}
print("2 in s:",2 in s) # 输出 True
#子集/超集判断
a = {1, 2}
b = {1, 2, 3}
print('a.issubset(b):',a.issubset(b)) # True(a 是 b 的子集)
print('b.issuperset(a):',b.issuperset(a)) # True(b 是 a 的超集)
#集合推导式
s = {x for x in range(10) if x % 2 == 0} # {0, 2, 4, 6, 8}
print("s:",s)
2 in s: True
a.issubset(b): True
b.issuperset(a): True
s: {0, 2, 4, 6, 8}
总结:
-
核心特性:无序、不重复、高效成员检测。
-
适用场景:去重、集合运算(如交集、并集)、快速查找元素。
字典
在Python3中字典(dictionary ,简写为dict)是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值 (key=>value
) 对用冒号 (:) 分割,每个对之间用逗号 (,) 分割,整个字典包括在花括号 ({}
) 中 ,格式如下:
dict = {key1 : value1, key2 : value2 }
键必须是唯一的,不可变,如字符串,数字或元组。
# 直接定义字典
d1 = {"name": "Alice", "age": 25}
print("d1",d1)
d2 = dict(name="Bob", age=30) # 通过关键字参数创建
print("d2",d2)
# 空字典
empty_dict = {} # 或 dict()# 从键值对列表创建
d3 = dict([("id", 1001), ("city", "Paris")]) # {'id': 1001, 'city': 'Paris'}
print("d3",d3)
d1 {'name': 'Alice', 'age': 25}
d2 {'name': 'Bob', 'age': 30}
d3 {'id': 1001, 'city': 'Paris'}
访问
d = {"name": "Alice", "age": 25}
print(d["name"]) # 直接访问 → "Alice"(键不存在会报 KeyError)
print(d.get("age")) # 安全访问 → 25(键不存在返回 None)
print(d.get("gender", "N/A")) # 指定默认值 → "N/A"
添加删除
#添加
d1 = {"name": "Alice"}
d1["age"] = 25 # 添加新键值对 → {"name": "Alice", "age": 25}
print('after add,d1:',d1)
d1["name"] = "Bob" # 修改现有键的值 → {"name": "Bob", "age": 25}
print('after update,d1:',d1)
#删除
del d1["age"]
print('after del,d1:',d1)
value = d1.pop("name")## 删除键 "name" 并返回值 → value
print("value:",value)
after add,d1: {'name': 'Alice', 'age': 25}
after update,d1: {'name': 'Bob', 'age': 25}
after del,d1: {'name': 'Bob'}
value: Bob
常用方法
#成员检测
d2 = {"a": 1, "b": 2}
print('"a" in d2:',"a" in d2) # 检查键是否存在 → True
print('1 in d2.values():',1 in d2.values()) # 检查值是否存在 → True
#遍历字典
price = {'包子': 12, '油条': 2,'豆腐脑': 5}
for key in price: # 遍历键print(key, price[key])
# for key, value in price.items(): # 同时遍历键值对
# print(key, value)
"a" in d2: True
1 in d2.values(): True
包子 12
油条 2
豆腐脑 5
应用:
#统计词频
text = "apple banana apple orange banana"
words = text.split()
frequency = {}
for word in words:frequency[word] = frequency.get(word, 0) + 1
print('frequency',frequency)
#配置
config = {"debug_mode": True,"max_connections": 10,"allowed_ports": [80, 443, 8080]
}
print("allowed_ports",config["allowed_ports"])
frequency {'apple': 2, 'banana': 2, 'orange': 1}
allowed_ports [80, 443, 8080]
总结
-
核心特性:键值对映射、快速查找、键不可变。
-
适用场景:数据关联存储(如JSON)、配置管理、缓存、快速查找数据。