本文将从多个方面详细解析Python中映射关系的使用方法和特点。
一、字典
字典是Python中最常用的映射关系。它由一系列无序的键值对组成,其中每个键都唯一对应一个值。
创建字典:
# 方法1:直接使用花括号
dict_1 = {'name': 'John', 'age': 20, 'city': 'New York'}
# 方法2:通过关键字参数创建
dict_2 = dict(name='John', age=20, city='New York')
访问字典:
# 获取value
name = dict_1['name']
age = dict_1.get('age')
# 判断key是否存在
if 'city' in dict_1:
print('city:', dict_1['city'])
遍历字典:
# 遍历key
for key in dict_1:
print(key, ':', dict_1[key])
# 遍历value
for value in dict_1.values():
print(value)
# 遍历键值对
for key, value in dict_1.items():
print(key, ':', value)
二、集合
集合是一系列无序的、唯一的元素组成的,不可变的数据类型。它是由哈希表实现的,其内部处理方式和字典相似。但是,集合键不映射任何值,因此键必须是唯一的。
创建集合:
set_1 = {1, 2, 3}
set_2 = set([1, 2, 3])
访问集合:
# 判断元素是否存在
if 1 in set_1:
print('1 in set_1')
# 遍历集合
for item in set_1:
print(item)
集合操作:
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
# 交集
print(set_a & set_b) # 输出 {3, 4}
# 并集
print(set_a | set_b) # 输出 {1, 2, 3, 4, 5, 6}
# 差集
print(set_a - set_b) # 输出 {1, 2}
# 对称差集
print(set_a ^ set_b) # 输出 {1, 2, 5, 6}
三、默认字典
默认字典是一种特殊的字典,它在创建时需要指定一个默认值,如果访问的键不存在,则返回指定的默认值。
创建默认字典:
from collections import defaultdict
def_1 = defaultdict(int)
def_2 = defaultdict(str)
def_3 = defaultdict(list)
def_4 = defaultdict(dict)
访问默认字典:
# 自动创建键值对
def_1['age'] += 1
def_2['name'] += 'John'
# 访问不存在的键
print(def_1['score']) # 输出 0
四、有序字典
有序字典是一种按照插入顺序有序的字典,其内部实现是通过维护一个双向链表来实现的。
创建有序字典:
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['c'] = 2
od['b'] = 3
print(od.keys()) # 输出 ['a', 'c', 'b']
遍历有序字典:
# 遍历key
for key in od:
print(key, ':', od[key])
# 遍历value
for value in od.values():
print(value)
# 遍历键值对
for key, value in od.items():
print(key, ':', value)
五、计数器
计数器是Python中的一个标准库,它提供了一个方便的方式来计算可哈希对象的频率。 计数器是字典的子类,其键是元素,值是计数。
创建计数器:
from collections import Counter
words = ['a', 'b', 'c', 'a', 'b', 'a']
counter = Counter(words)
print(counter) # 输出: Counter({'a': 3, 'b': 2, 'c': 1})
访问计数器:
print(counter['a']) # 输出 3
print(counter['d']) # 输出 0
计数器操作:
counter_1 = Counter(a=3, b=2)
counter_2 = Counter(a=1, b=4)
# 相加
print(counter_1 + counter_2) # 输出 Counter({'b': 6, 'a': 4})
# 相减
print(counter_1 - counter_2) # 输出 Counter({'a': 2})
# 取交集
print(counter_1 & counter_2) # 输出 Counter({'a': 1, 'b': 2})
# 取并集
print(counter_1 | counter_2) # 输出 Counter({'b': 4, 'a': 3, 'c': 1})
总结
本文详细介绍了Python中常用的映射关系,包括字典、集合、默认字典、有序字典和计数器。我们通过实例化和操作这些结构来演示它们的主要用途和特点。