Python元祖及字典小练习
发布人:shili8
发布时间:2025-02-23 13:09
阅读次数:0
**Python 元祖及字典小练习**
### 一、元祖基本操作元祖(tuple)是 Python 中的一种不可变序列类型。它的元素可以是任意类型,包括数字、字符串、列表等。
####1. 元祖创建
# 使用圆括号创建元祖my_tuple = (1,2,3) print(my_tuple) # 输出: (1,2,3) # 使用tuple()函数创建元祖my_tuple = tuple([1,2,3]) print(my_tuple) # 输出: (1,2,3)
####2. 元祖索引
# 索引元祖中的元素my_tuple = (1,2,3) print(my_tuple[0]) # 输出:1print(my_tuple[-1]) # 输出:3
####3. 元祖切片
# 切片元祖中的元素my_tuple = (1,2,3) print(my_tuple[:2]) # 输出: (1,2) print(my_tuple[1:]) # 输出: (2,3)
####4. 元祖长度
# 获取元祖的长度my_tuple = (1,2,3) print(len(my_tuple)) # 输出:3
### 二、字典基本操作字典(dictionary)是 Python 中的一种可变序列类型。它的元素可以是任意类型,包括数字、字符串、列表等。
####1. 字典创建
# 使用花括号创建字典my_dict = {"name": "John", "age":30} print(my_dict) # 输出: {'name': 'John', 'age':30} # 使用dict()函数创建字典my_dict = dict(name="John", age=30) print(my_dict) # 输出: {'name': 'John', 'age':30}
####2. 字典键值对
# 获取字典中的键值对my_dict = {"name": "John", "age":30} print(my_dict["name"]) # 输出: Johnprint(my_dict.get("name")) # 输出: John
####3. 字典长度
# 获取字典的长度my_dict = {"name": "John", "age":30} print(len(my_dict)) # 输出:2
### 三、元祖和字典的比较元祖和字典都是 Python 中的一种序列类型,但它们有着不同的特点。
####1. 元祖不可变,字典可变
# 元祖不可变my_tuple = (1,2,3) try: my_tuple[0] =4except TypeError as e: print(e) # 输出: 'tuple' object does not support item assignment# 字典可变my_dict = {"name": "John", "age":30} my_dict["name"] = "Jane" print(my_dict) # 输出: {'name': 'Jane', 'age':30}
####2. 元祖长度固定,字典长度动态
# 元祖长度固定my_tuple = (1,2,3) try: my_tuple.append(4) except AttributeError as e: print(e) # 输出: 'tuple' object has no attribute 'append' # 字典长度动态my_dict = {"name": "John", "age":30} my_dict["country"] = "USA" print(len(my_dict)) # 输出:3
### 四、元祖和字典的应用元祖和字典在 Python 中有着广泛的应用。
####1. 元祖用于存储不可变数据
# 使用元祖存储不可变数据my_tuple = (1,2,3) print(my_tuple) # 输出: (1,2,3) # 使用字典存储可变数据my_dict = {"name": "John", "age":30} print(my_dict) # 输出: {'name': 'John', 'age':30}
####2. 元祖用于表示坐标或位置
# 使用元祖表示坐标point = (3,4) print(point) # 输出: (3,4) # 使用字典表示坐标point = {"x":3, "y":4} print(point) # 输出: {'x':3, 'y':4}
####3. 元祖用于表示颜色或模式
# 使用元祖表示颜色color = (255,0,0) print(color) # 输出: (255,0,0) # 使用字典表示颜色color = {"red":255, "green":0, "blue":0} print(color) # 输出: {'red':255, 'green':0, 'blue':0}
### 五、总结元祖和字典是 Python 中两种常见的序列类型。它们有着不同的特点,分别用于存储不可变数据和可变数据。元祖用于表示坐标或位置,而字典用于表示颜色或模式。通过理解元祖和字典的特点和应用,我们可以更好地使用 Python 来解决问题。