Python中常见数据结构:列表、字典和集合的实例解析
在Python中,常见的数据结构包括列表(List)、字典(Dictionary)和集合(Set)。下面是对这些数据结构实例解析:
- 列表(List)
例子:
# 创建一个空列表
empty_list = []
# 创建一个包含整数的列表
number_list = [1, 2, 3, 4]
# 访问列表中的元素
print(number_list[0]) # 输出: 1
# 修改列表元素
number_list[2] = 5
print(number_list) # 输出: [1, 2, 5, 4]
- 字典(Dictionary)
例子:
# 创建一个空字典
empty_dict = {}
# 创建一个包含键值对的字典
student = {'name': 'John', 'age': 20, 'courses': ['Math', 'Science']}
# 访问字典中的值
print(student['name']) # 输出: John
# 修改字典中的值
student['age'] = 21
print(student) # 输出: {'name': 'John', 'age': 21, 'courses': ['Math', 'Science']}
# 删除字典中的键
del student['courses']
print(student) # 输出: {'name': 'John', 'age': 21, 'courses': []}
- 集合(Set)
例子:
# 创建一个空集合
empty_set = set()
# 创建一个包含元素的集合
numbers = {1, 2, 3, 4, 5}
unique_numbers = numbers.difference(numbers) # 仅保留第一个实例
print(unique_numbers) # 输出: {1}
# 添加、删除和检查集合中的元素
unique_numbers.add(6)
print(unique_numbers) # 输出: {1, 6}
unique_numbers.remove(1)
print(unique_numbers) # 输出: {6}
if 2 in unique_numbers:
print("2存在于集合中。")
else:
print("2不存在于集合中。")
# 结构检查
if not empty_set:
print("空集合存在!")
else:
print("空集合不存在!")
以上就是Python中常见数据结构的实例解析。
还没有评论,来说两句吧...