本文详细介绍Python中四种主要的基础数据类型:字典、元组、列表和集合。
一、字典
1、字典是Python中最重要的数据结构之一。它是一种可变、无序、可重复的键值对容器。每个元素包含一个键和对应的值,键必须是唯一不重复的。我们可以通过键访问相应的值,而不是通过索引访问,这使得字典可以非常快速地查询元素。
# 创建字典 dict1 = {'name': 'Alice', 'age': 20, 'gender': 'female'} # 遍历字典 for key, value in dict1.items(): print(key, value) # 输出:name Alice # age 20 # gender female # 访问元素 print(dict1['age']) # 20 # 添加元素 dict1['major'] = 'Computer Science' # 删除元素 del dict1['gender']
2、字典的常用内置方法
(1)copy()方法用于复制字典。
(2)clear()方法用于清空字典中所有元素。
(3)get()方法用于根据键获取对应的值,如果键不存在时可以设置默认值。
# 代码示例 dict2 = dict1.copy() dict1.clear() print(dict2) print(dict1) print(dict2.get('gender', 'unknown'))
二、元组
1、元组是不可变的序列,主要用于存储异构的数据类型。元组定义后不能再进行修改,但可以通过索引找到相应的元素。
# 创建元组 tuple1 = (1, 2, 'a', 'b') # 访问元素 print(tuple1[0]) # 1 # 遍历元组 for item in tuple1: print(item) # 输出:1 # 2 # a # b
2、元组的常用操作
(1)元组拼接:可以通过“+”符号进行拼接,生成一个新的元组。
(2)元组重复:可以通过“*”符号进行重复,生成一个新的元组。
(3)元组元素删除:元组中的元素无法直接删除,可以使用切片来实现。
# 代码示例 tuple2 = (3, 4) tuple3 = tuple1 + tuple2 tuple4 = tuple1 * 2 tuple1 = tuple1[:2] + tuple1[3:] print(tuple3) print(tuple4) print(tuple1)
三、列表
1、列表是Python中最常用、最基础的数据类型之一,它是一种有序、可重复可变的序列,可以保存任何类型的数据。列表中的元素可以按照索引进行访问、添加、修改和删除。
# 创建列表 list1 = [1, 2, 3, 4] # 访问元素 print(list1[0]) # 1 # 修改元素 list1[0] = 5 # 删除元素 list1.pop() # 遍历列表 for item in list1: print(item) # 输出:5 # 2 # 3
2、列表的常用操作
(1)列表拼接:可以通过“+”符号进行拼接,生成一个新的列表。
(2)列表元素重复:可以通过“*”符号进行重复,生成一个新的列表。
(3)列表元素删除:可以使用del语句或者remove()方法进行删除。
# 代码示例 list2 = [5, 6] list3 = list1 + list2 list4 = list1 * 2 del list1[0] list1.remove(3) print(list3) print(list4) print(list1)
四、集合
1、集合是一种无序的、可变的容器,它可以去重、交集、并集、差集等操作。集合中的元素必须是不可变的类型,例如字符串、数字、元组等。
# 创建集合 set1 = {1, 2, 3, 3, 4, 5} # 遍历集合 for item in set1: print(item) # 输出:1 # 2 # 3 # 4 # 5 # 添加元素 set1.add(6) # 删除元素 set1.remove(2) # 集合操作 set2 = {3, 4, 5, 6, 7} set_union = set1.union(set2) # 并集 set_intersection = set1.intersection(set2) # 交集 set_difference = set1.difference(set2) # 差集 print(set_union) print(set_intersection) print(set_difference)
2、集合的常用方法
(1)copy()方法用于复制集合。
(2)clear()方法用于清空集合中所有元素。
(3)discard()方法用于删除集合中指定的元素,如果元素不存在则不进行操作。
# 代码示例 set3 = set1.copy() set1.clear() set3.discard(2) print(set3) print(set1)