python数据类型用法
时间: 2025-01-16 15:07:34 浏览: 20
Python 数据类型概述
Python 提供了多种内置数据类型用于存储不同类型的信息。主要的数据类型包括:
- Number(数字)
- String(字符串)
- Boolean(布尔类型)
- List(列表)
- Tuple(元组)
- Set(集合)
- Dictionary(字典)
这些基本数据结构支持复杂的应用程序开发需求。
数字 (Numbers)
整数、浮点数以及复数都属于这一类别,在实际编程过程中可以直接赋值给变量使用[^1]。
integer_example = 42 # 整型
floating_point_example = 3.14 # 浮点型
complex_number_example = 2 + 3j # 复数
字符串 (Strings)
字符串是由字符组成的序列,可以使用单引号或双引号表示。支持索引操作获取特定位置上的字符,并允许切片访问子串。
string_example = "Hello, world!"
first_character = string_example[0] # 获取第一个字符 'H'
substring_example = string_example[:5] # 切片得到前五个字符 'Hello'
布尔值 (Booleans)
仅包含两个可能的值 True
和 False
. 这种简单的二进制逻辑对于条件判断非常重要.
boolean_true = True
boolean_false = False
is_equal = (1 == 1) # 结果为 True
not_equal = ("hello" != "world") # 结果也为 True
列表 (Lists)
列表是一种可变容器模型,能够容纳任意数量的不同种类项。可以通过方括号创建并利用索引来读写其中元素[^4].
list_of_numbers = [1, 2, 3, 4]
mixed_list = ["apple", 42, 3.14]
# 修改列表中的某个元素
mixed_list[0] = "orange"
# 添加新成员到列表末端
list_of_numbers.append(5)
元组 (Tuples)
类似于列表但是不可更改;一旦初始化完成就不能再修改其内部任何一项的内容。适合用来保存固定不变的一系列项目.
tuple_of_coordinates = (10, 20)
another_tuple = ('a', 'b', 'c')
# 尝试改变元组会引发错误 TypeError: 'tuple' object does not support item assignment.
# another_tuple[0] = 'z'
集合 (Sets)
无序且不重复元素集合作为代表性的抽象数据类型之一。提供了高效的交集、差集运算等功能.
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union_set = set_a | set_b # 并集 {1, 2, 3, 4, 5}
intersection_set = set_a & set_b # 交集 {3}
difference_set = set_a - set_b # 差集 {1, 2}
字典 (Dictionaries)
字典是以键值对形式存在的映射关系,每个键关联着唯一的一个值。通过花括号 {}
来声明字典实例,而键与对应的值之间则用冒号分隔开.
person_info = {"name": "Alice", "age": 28, "city": "Beijing"}
# 访问字典内的条目
print(person_info["name"]) # 输出 Alice
# 更新现有条目的值
person_info["age"] = 29
# 向字典中增加新的条目
person_info["country"] = "China"
枚举类型 (Enums)
从 Python 3.4 开始引入的标准库模块 enum
支持定义枚举类,使得代码更加清晰易懂[^2]. 下面是一个简单例子展示如何创建和应用枚举:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
favorite_color = Color.RED
if favorite_color is Color.BLUE:
print('The color blue was chosen.')
else:
print(f'The selected color is not blue but rather {favorite_color.name}.')
相关推荐


















