Python 数据类型详解 - 深度教程
目录
数据类型概述
Python 的类型系统
python
# Python 是动态类型语言
x = 5 # int
x = "hello" # str (可以改变类型)
# 但同时是强类型语言
print("5" + 5) # TypeError: 不会自动转换
# 查看类型
type(5) # <class 'int'>
type("hello") # <class 'str'>
type([1, 2, 3]) # <class 'list'>
# isinstance 检查
isinstance(5, int) # True
isinstance("hello", str) # True
isinstance([1, 2], (list, tuple)) # True内置数据类型分类
数字类型:int, float, complex
序列类型:list, tuple, range, str
映射类型:dict
集合类型:set, frozenset
布尔类型:bool
二进制类型:bytes, bytearray, memoryview
空类型:NoneType数字类型
整数(int)
python
# Python 3 的 int 没有大小限制
x = 1234567890123456789012345678901234567890
print(x) # 正常工作
# 不同进制表示
binary = 0b1010 # 二进制(10)
octal = 0o12 # 八进制(10)
hexadecimal = 0x0A # 十六进制(10)
decimal = 10 # 十进制
# 进制转换
num = 255
bin(num) # '0b11111111'
oct(num) # '0o377'
hex(num) # '0xff'
# 从字符串转换
int('1010', 2) # 10 (从二进制)
int('12', 8) # 10 (从八进制)
int('A', 16) # 10 (从十六进制)
# 数字分隔符(Python 3.6+)
million = 1_000_000
binary = 0b_1111_0000
hex_num = 0x_FF_FF
# 数学运算
print(10 / 3) # 3.3333...
print(10 // 3) # 3 (整除)
print(10 % 3) # 1 (取余)
print(divmod(10, 3)) # (3, 1) (商和余数)
# 位运算
print(5 & 3) # 1 (AND)
print(5 | 3) # 7 (OR)
print(5 ^ 3) # 6 (XOR)
print(~5) # -6 (NOT)
print(5 << 1) # 10 (左移)
print(5 >> 1) # 2 (右移)浮点数(float)
python
# 基本用法
pi = 3.14159
e = 2.71828
# 科学计数法
speed_of_light = 3.0e8 # 3.0 * 10^8
avogadro = 6.022e23
# 精度问题
print(0.1 + 0.2) # 0.30000000000000004
# 解决精度问题:使用 decimal
from decimal import Decimal
x = Decimal('0.1')
y = Decimal('0.2')
print(x + y) # 0.3
# 特殊值
inf = float('inf') # 正无穷
neg_inf = float('-inf') # 负无穷
nan = float('nan') # Not a Number
import math
print(math.isinf(inf)) # True
print(math.isnan(nan)) # True
# 浮点数运算
import math
print(math.floor(3.7)) # 3 (向下取整)
print(math.ceil(3.2)) # 4 (向上取整)
print(round(3.5)) # 4 (四舍五入)
print(round(3.14159, 2)) # 3.14
# 浮点数比较
a = 0.1 + 0.2
b = 0.3
print(a == b) # False
# 正确的比较方法
import math
print(math.isclose(a, b)) # True
# 或使用 epsilon
epsilon = 1e-9
print(abs(a - b) < epsilon) # True复数(complex)
python
# 创建复数
z1 = 3 + 4j
z2 = complex(3, 4)
# 访问实部和虚部
print(z1.real) # 3.0
print(z1.imag) # 4.0
# 复数运算
z1 = 3 + 4j
z2 = 1 + 2j
print(z1 + z2) # (4+6j)
print(z1 - z2) # (2+2j)
print(z1 * z2) # (-5+10j)
print(z1 / z2) # (2.2-0.4j)
# 共轭复数
print(z1.conjugate()) # (3-4j)
# 模(绝对值)
print(abs(z1)) # 5.0
# cmath 模块
import cmath
print(cmath.phase(z1)) # 0.927... (相位角)
print(cmath.polar(z1)) # (5.0, 0.927...) (极坐标形式)math 模块
python
import math
# 常量
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
print(math.tau) # 6.283185307179586 (2π)
print(math.inf) # 无穷大
# 三角函数(弧度)
print(math.sin(math.pi / 2)) # 1.0
print(math.cos(0)) # 1.0
print(math.tan(math.pi / 4)) # 1.0
# 角度转换
print(math.degrees(math.pi)) # 180.0
print(math.radians(180)) # 3.141592...
# 指数和对数
print(math.exp(1)) # e^1 = 2.718...
print(math.log(10)) # ln(10) = 2.302...
print(math.log10(100)) # log10(100) = 2.0
print(math.log2(8)) # log2(8) = 3.0
# 平方根和幂
print(math.sqrt(16)) # 4.0
print(math.pow(2, 10)) # 1024.0
# 其他函数
print(math.factorial(5)) # 120
print(math.gcd(48, 18)) # 6 (最大公约数)
print(math.lcm(12, 18)) # 36 (最小公倍数)random 模块
python
import random
# 随机浮点数 [0.0, 1.0)
print(random.random())
# 随机整数
print(random.randint(1, 10)) # 1-10(包含)
print(random.randrange(0, 10, 2)) # 0,2,4,6,8
# 随机选择
colors = ['red', 'green', 'blue']
print(random.choice(colors))
# 随机抽样
print(random.sample(range(100), 5)) # 5个不重复的数
# 洗牌
deck = list(range(52))
random.shuffle(deck)
# 随机分布
print(random.uniform(1.0, 10.0)) # 均匀分布
print(random.gauss(0, 1)) # 正态分布
# 设置随机种子(可重现结果)
random.seed(42)
print(random.random()) # 总是相同字符串详解
字符串创建
python
# 单引号和双引号
s1 = 'Hello'
s2 = "World"
# 三引号(多行字符串)
s3 = """This is
a multi-line
string"""
s4 = '''Another
multi-line
string'''
# 原始字符串(忽略转义)
path = r"C:\Users\name\folder" # 不会把 \n \f 解释为转义
# f-string(格式化字符串)
name = "Alice"
age = 25
s5 = f"My name is {name}, I'm {age} years old"
# 字符串拼接
s = "Hello" + " " + "World"
s = "Hello " "World" # 隐式拼接字符串索引和切片
python
text = "Python"
# 索引
print(text[0]) # 'P' (第一个字符)
print(text[-1]) # 'n' (最后一个字符)
print(text[-2]) # 'o' (倒数第二个)
# 切片 [start:end:step]
print(text[0:3]) # 'Pyt' (0,1,2)
print(text[:3]) # 'Pyt' (省略start)
print(text[2:]) # 'thon' (省略end)
print(text[:]) # 'Python' (复制)
# 步长
print(text[::2]) # 'Pto' (每隔一个)
print(text[::-1]) # 'nohtyP' (反转)
print(text[1::2]) # 'yhn'
# 切片技巧
s = "Hello World"
print(s[:-6]) # 'Hello' (去除后6个字符)
print(s[6:]) # 'World' (从第7个开始)
print(s.split()[0]) # 'Hello' (第一个单词)
print(s.split()[1]) # 'World' (第二个单词)字符串方法
大小写转换
python
text = "Hello World"
print(text.upper()) # 'HELLO WORLD'
print(text.lower()) # 'hello world'
print(text.title()) # 'Hello World'
print(text.capitalize()) # 'Hello world'
print(text.swapcase()) # 'hELLO wORLD'
# 判断
print(text.isupper()) # False
print(text.islower()) # False
print(text.istitle()) # True查找和替换
python
text = "Hello World, Hello Python"
# 查找
print(text.find("World")) # 6 (首次出现的位置)
print(text.find("Java")) # -1 (未找到)
print(text.rfind("Hello")) # 13 (最后一次出现)
print(text.index("World")) # 6 (同find,但未找到会抛异常)
print(text.count("Hello")) # 2 (出现次数)
# 判断
print(text.startswith("Hello")) # True
print(text.endswith("Python")) # True
print("World" in text) # True
# 替换
print(text.replace("Hello", "Hi")) # 全部替换
print(text.replace("Hello", "Hi", 1)) # 只替换1次分割和连接
python
# 分割
text = "apple,banana,orange"
fruits = text.split(",") # ['apple', 'banana', 'orange']
text = "one two three"
words = text.split() # ['one', 'two', 'three'] (自动去除多余空格)
text = "apple|banana|orange"
fruits = text.split("|", 1) # ['apple', 'banana|orange'] (限制分割次数)
# 按行分割
multiline = "line1\nline2\nline3"
lines = multiline.splitlines() # ['line1', 'line2', 'line3']
# 连接
fruits = ['apple', 'banana', 'orange']
text = ", ".join(fruits) # 'apple, banana, orange'
text = "\n".join(fruits) # 'apple\nbanana\norange'
# 分区
text = "user@example.com"
before, sep, after = text.partition("@")
# before='user', sep='@', after='example.com'去除空白
python
text = " Hello World \n"
print(text.strip()) # 'Hello World' (去除两端空白)
print(text.lstrip()) # 'Hello World \n' (去除左侧)
print(text.rstrip()) # ' Hello World' (去除右侧)
# 去除指定字符
url = "https://example.com/"
print(url.strip("https://")) # 'example.com/'
print(url.rstrip("/")) # 'https://example.com'对齐和填充
python
text = "Python"
# 居中、左对齐、右对齐
print(text.center(20)) # ' Python '
print(text.center(20, '-')) # '-------Python-------'
print(text.ljust(20, '-')) # 'Python--------------'
print(text.rjust(20, '-')) # '--------------Python'
# 填充零
num = "42"
print(num.zfill(5)) # '00042'判断字符类型
python
# 字母和数字
print("abc123".isalnum()) # True
print("abc".isalpha()) # True
print("123".isdigit()) # True
print("123".isnumeric()) # True
print("abc123".isalpha()) # False
# 空白和可打印
print(" ".isspace()) # True
print("Hello".isprintable()) # True
# 标识符
print("variable_name".isidentifier()) # True
print("2variable".isidentifier()) # False字符串格式化
f-string(推荐)
python
name = "Alice"
age = 25
score = 95.5
# 基本用法
print(f"Name: {name}, Age: {age}")
# 表达式
print(f"{name.upper()}")
print(f"{age + 1}")
print(f"{2 ** 10}")
# 格式控制
print(f"{score:.1f}") # 95.5 (1位小数)
print(f"{score:.0f}") # 96 (整数)
print(f"{score:06.1f}") # 0095.5 (填充)
# 对齐
print(f"{name:>10}") # ' Alice' (右对齐)
print(f"{name:<10}") # 'Alice ' (左对齐)
print(f"{name:^10}") # ' Alice ' (居中)
print(f"{name:*^10}") # '**Alice***' (用*填充)
# 数字格式
num = 1234567
print(f"{num:,}") # '1,234,567' (千位分隔)
print(f"{num:_}") # '1_234_567'
# 百分比
ratio = 0.85
print(f"{ratio:.1%}") # '85.0%'
# 日期时间
from datetime import datetime
now = datetime.now()
print(f"{now:%Y-%m-%d %H:%M:%S}")
# 调试(Python 3.8+)
x = 10
y = 20
print(f"{x=}, {y=}") # x=10, y=20str.format()
python
# 位置参数
print("{} {}".format("Hello", "World"))
print("{0} {1}".format("Hello", "World"))
print("{1} {0}".format("Hello", "World")) # World Hello
# 关键字参数
print("{name} is {age} years old".format(name="Alice", age=25))
# 混合
print("{0}, {name}!".format("Hello", name="World"))
# 格式控制
print("{:.2f}".format(3.14159)) # 3.14
print("{:>10}".format("test")) # ' test'字符串编码
python
# 编码(str -> bytes)
text = "Hello 世界"
encoded = text.encode('utf-8')
print(encoded) # b'Hello \xe4\xb8\x96\xe7\x95\x8c'
# 解码(bytes -> str)
decoded = encoded.decode('utf-8')
print(decoded) # 'Hello 世界'
# 不同编码
print(text.encode('gbk'))
print(text.encode('ascii', errors='ignore')) # 忽略错误
# 处理 Unicode
print(ord('A')) # 65 (字符转 Unicode 码点)
print(chr(65)) # 'A' (码点转字符)
print('\u4e2d') # '中' (Unicode 转义)字符串不可变性
python
text = "Python"
# ❌ 不能修改
text[0] = 'J' # TypeError
# ✅ 创建新字符串
text = 'J' + text[1:] # 'Jython'
# 字符串拼接效率
# ❌ 低效(每次都创建新字符串)
result = ""
for i in range(1000):
result += str(i)
# ✅ 高效
result = "".join(str(i) for i in range(1000))列表(List)
列表创建
python
# 空列表
empty = []
empty = list()
# 初始化列表
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True, [1, 2]]
# 使用 list() 构造
numbers = list(range(5)) # [0, 1, 2, 3, 4]
chars = list("Python") # ['P', 'y', 't', 'h', 'o', 'n']
# 列表推导式
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
# 重复
zeros = [0] * 10 # [0, 0, 0, ...]
# 二维列表
matrix = [[0] * 3 for _ in range(3)] # 3x3 矩阵
# [[0, 0, 0],
# [0, 0, 0],
# [0, 0, 0]]列表操作
python
numbers = [1, 2, 3, 4, 5]
# 访问元素
print(numbers[0]) # 1
print(numbers[-1]) # 5
# 修改元素
numbers[0] = 10
print(numbers) # [10, 2, 3, 4, 5]
# 切片
print(numbers[1:3]) # [2, 3]
print(numbers[::2]) # [10, 3, 5]
# 切片赋值
numbers[1:3] = [20, 30]
print(numbers) # [10, 20, 30, 4, 5]
numbers[1:3] = [] # 删除元素
print(numbers) # [10, 4, 5]列表方法
python
fruits = ['apple', 'banana']
# 添加元素
fruits.append('orange') # 末尾添加
fruits.insert(1, 'grape') # 指定位置插入
fruits.extend(['mango', 'peach']) # 扩展列表
# 删除元素
fruits.remove('banana') # 删除第一个匹配项
last = fruits.pop() # 删除并返回最后一个
second = fruits.pop(1) # 删除并返回指定位置
del fruits[0] # 删除指定位置
fruits.clear() # 清空列表
# 查找
fruits = ['apple', 'banana', 'orange']
print(fruits.index('banana')) # 1
print(fruits.count('apple')) # 1
print('banana' in fruits) # True
# 排序
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort() # 原地排序
numbers.sort(reverse=True) # 降序
fruits = ['banana', 'apple', 'cherry']
fruits.sort(key=len) # 按长度排序
# sorted() 返回新列表
numbers = [3, 1, 4, 1, 5]
sorted_numbers = sorted(numbers)
# 反转
numbers.reverse() # 原地反转
reversed_numbers = list(reversed(numbers)) # 返回新列表
# 复制
copy1 = fruits.copy()
copy2 = fruits[:]
copy3 = list(fruits)列表推导式
python
# 基本形式
squares = [x**2 for x in range(10)]
# 带条件
evens = [x for x in range(20) if x % 2 == 0]
# 多重循环
pairs = [(x, y) for x in range(3) for y in range(3)]
# [(0,0), (0,1), (0,2), (1,0), ...]
# 嵌套列表推导
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 转置矩阵
transposed = [[row[i] for row in matrix] for i in range(3)]
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# 带 if-else
result = [x if x % 2 == 0 else -x for x in range(10)]
# [0, -1, 2, -3, 4, -5, 6, -7, 8, -9]列表常见操作
python
numbers = [1, 2, 3, 4, 5]
# 长度、最大值、最小值、求和
print(len(numbers)) # 5
print(max(numbers)) # 5
print(min(numbers)) # 1
print(sum(numbers)) # 15
# 拼接
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2 # [1, 2, 3, 4, 5, 6]
# 重复
repeated = [1, 2] * 3 # [1, 2, 1, 2, 1, 2]
# 成员判断
print(3 in numbers) # True
print(10 not in numbers) # True
# enumerate(带索引遍历)
for index, value in enumerate(['a', 'b', 'c']):
print(f"{index}: {value}")
# zip(并行遍历)
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")元组(Tuple)
元组创建
python
# 空元组
empty = ()
empty = tuple()
# 单元素元组(注意逗号)
single = (1,) # ✅
not_tuple = (1) # ❌ 这是整数
# 多元素元组
numbers = (1, 2, 3, 4, 5)
mixed = (1, "hello", 3.14, True)
# 不带括号
point = 1, 2, 3 # 也是元组
# 使用 tuple() 构造
numbers = tuple([1, 2, 3])
chars = tuple("Python")元组操作
python
point = (10, 20, 30)
# 访问元素
print(point[0]) # 10
print(point[-1]) # 30
# 切片
print(point[1:]) # (20, 30)
# ❌ 不能修改
point[0] = 15 # TypeError
# 但可以包含可变对象
data = ([1, 2], [3, 4])
data[0].append(3) # ✅ 修改列表内容
print(data) # ([1, 2, 3], [3, 4])
# 元组方法
numbers = (1, 2, 3, 2, 1)
print(numbers.count(2)) # 2
print(numbers.index(3)) # 2
# 元组拼接和重复
t1 = (1, 2)
t2 = (3, 4)
print(t1 + t2) # (1, 2, 3, 4)
print(t1 * 3) # (1, 2, 1, 2, 1, 2)元组解包
python
# 基本解包
point = (10, 20, 30)
x, y, z = point
# 交换变量
a, b = 1, 2
a, b = b, a
# 扩展解包
first, *rest = [1, 2, 3, 4, 5]
# first = 1, rest = [2, 3, 4, 5]
head, *middle, tail = [1, 2, 3, 4, 5]
# head = 1, middle = [2, 3, 4], tail = 5
# 忽略值
x, _, z = (10, 20, 30) # 忽略中间值
# 函数返回多值
def get_point():
return 10, 20, 30
x, y, z = get_point()元组 vs 列表
python
# 相同点
t = (1, 2, 3)
l = [1, 2, 3]
print(t[0]) # 访问元素
print(len(t)) # 长度
print(2 in t) # 成员判断
# 不同点
# 1. 元组不可变
l[0] = 10 # ✅
# t[0] = 10 # ❌ TypeError
# 2. 性能:元组更快
import sys
print(sys.getsizeof(t)) # 更小
print(sys.getsizeof(l)) # 更大
# 3. 用途:元组用于不可变数据
point = (10, 20) # 坐标
person = ("Alice", 25) # 记录
# 4. 字典键:元组可以,列表不行
locations = {
(0, 0): "origin",
(1, 1): "diagonal"
}命名元组
python
from collections import namedtuple
# 定义命名元组
Point = namedtuple('Point', ['x', 'y'])
# 创建实例
p = Point(10, 20)
print(p.x, p.y) # 10 20
# 也支持索引
print(p[0], p[1]) # 10 20
# 方法
print(p._asdict()) # {'x': 10, 'y': 20}
# 实际应用
Person = namedtuple('Person', ['name', 'age', 'email'])
alice = Person('Alice', 25, 'alice@example.com')
print(alice.name) # Alice
print(alice.age) # 25由于篇幅限制,我将继续创建剩余部分...
