python - 数据类型

Python 支持多种数据类型,分为 基本数据类型 (内置)和 复合数据类型(容器类型)。以下是 Python 主要数据类型的详细总结:


1. 基本数据类型(内置类型)

1.1 数值类型(Numbers)

  • int :整数(如 10, -5, 0
  • float :浮点数(如 3.14, -0.001, 2.0
  • complex :复数(如 1 + 2j
  • bool :布尔值(True / False,是 int 的子类)
python 复制代码
a = 10       # int
b = 3.14     # float
c = 1 + 2j   # complex
d = True     # bool (True=1, False=0)

1.2 字符串(str

  • 表示文本数据,用单引号 ' 或双引号 " 包裹。
  • 支持索引、切片、拼接、格式化等操作。
python 复制代码
s = "Hello, Python"
print(s[0])      # 'H'(索引)
print(s[7:13])   # 'Python'(切片)
print("Hi" + s)  # 'HiHello, Python'(拼接)

1.3 空值(None

  • 表示"无"或"空",类似于其他语言的 ``。
python 复制代码
x = None
print(x)  # None

2. 复合数据类型(容器类型)

2.1 列表(list

  • 可变有序的序列,支持混合类型。
  • 用方括号 [] 表示。
python 复制代码
nums = [1, 2, 3, "a", "b"]
nums[0] = 100  # 修改元素
nums.append(4) # 添加元素
print(nums)    # [100, 2, 3, 'a', 'b', 4]

2.2 元组(tuple

  • 不可变有序 的序列,用圆括号 () 表示。
  • 比列表更轻量,适合存储常量数据。
python 复制代码
colors = ("red", "green", "blue")
print(colors[1])  # 'green'
# colors[1] = "yellow"  # 报错:元组不可修改

2.3 字典(dict

  • 键值对(Key-Value) 存储,用花括号 {} 表示。
  • 键必须是不可变类型(如 str, int, tuple)。
python 复制代码
person = {"name": "Alice", "age": 25}
print(person["name"])  # 'Alice'
person["age"] = 26     # 修改值
person["city"] = "NY"  # 添加键值对

2.4 集合(set

  • 无序不重复 的元素集合,用花括号 {}set() 创建。
  • 支持交集 &、并集 |、差集 - 等操作。
python 复制代码
s = {1, 2, 3, 2}  # 自动去重:{1, 2, 3}
s.add(4)         # 添加元素
print(s)         # {1, 2, 3, 4}

2.5 字符串(str

  • 虽然字符串是基本类型,但它也支持类似容器的操作(如索引、切片)。
python 复制代码
s = "hello"
print(s[1:4])  # 'ell'(切片)

3. 类型转换

Python 提供内置函数进行类型转换:

python 复制代码
# 数值转换
x = int("10")      # 字符串 → 整数
y = float("3.14")  # 字符串 → 浮点数
z = str(100)       # 整数 → 字符串
 
# 容器类型转换
lst = list((1, 2, 3))   # 元组 → 列表
tup = tuple([4, 5, 6])  # 列表 → 元组
s = set([1, 2, 2, 3])   # 列表 → 集合(去重)

4. 类型检查

使用 type()isinstance() 检查数据类型:

python 复制代码
x = 10
print(type(x))          # <class 'int'>
print(isinstance(x, int))  # True

5. 总结

类型 分类 特点 示例
int 数值 整数 10, -5
float 数值 浮点数 3.14, -0.5
bool 数值 布尔值 True, False
str 序列 字符串 "hello"
list 序列 可变有序 [1, 2, "a"]
tuple 序列 不可变有序 (1, 2, "a")
dict 映射 键值对 {"name": "Alice"}
set 集合 无序不重复 {1, 2, 3}
None 特殊 空值 None

6. 扩展:可变 vs 不可变

  • 可变(Mutable)list, dict, set(可修改内容)。
  • 不可变(Immutable)int, float, str, tuple(创建后不能修改)。
python 复制代码
# 不可变示例(字符串不能直接修改)
s = "hello"
# s[0] = "H"  # 报错
s = "H" + s[1:]  # 重新赋值
 
# 可变示例(列表可以修改)
lst = [1, 2, 3]
lst[0] = 100  # 直接修改
相关推荐
多恩Stone1 小时前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc
xiaopengbc1 小时前
在 Python 中实现观察者模式的具体步骤是什么?
开发语言·python·观察者模式
Python大数据分析@1 小时前
python用selenium怎么规避检测?
开发语言·python·selenium·网络爬虫
ThreeAu.2 小时前
Miniconda3搭建Selenium的python虚拟环境全攻略
开发语言·python·selenium·minicoda·python环境配置
偷心伊普西隆2 小时前
Python EXCEL 理论探究:格式转换时处理缺失值方法
python·excel
精灵vector3 小时前
LLMCompiler:基于LangGraph的并行化Agent架构高效实现
人工智能·python·langchain
java1234_小锋3 小时前
Scikit-learn Python机器学习 - 特征降维 压缩数据 - 特征选择 - 移除低方差特征(VarianceThreshold)
python·机器学习·scikit-learn
万邦科技Lafite3 小时前
实战演练:通过API获取商品详情并展示
大数据·数据库·python·开放api接口