第2章:类型与操作(Types and Operations)
一、导读
1.1 本章学习目标
第2章深入讲解 Python 的内置类型和操作。Python 的类型系统丰富而灵活,理解这些类型是写出高效 Python 代码的基础。
本章的核心学习目标包括:
- 掌握数字类型的操作:整数、浮点数、复数、布尔值。
- 深入理解字符串:格式化、切片、方法、编码。
- 掌握列表和元组:可变序列与不可变序列的区别。
- 理解字典和集合:哈希表的实现和应用。
- 学会类型转换:不同类型之间的转换规则。
1.2 为什么第二章如此重要
类型是编程的基础。Python 的内置类型经过高度优化,理解它们的特性和操作方式,能帮助你写出高效、优雅的代码。
1.3 核心问题引导
Python 的整数为什么没有溢出问题?
字符串的切片操作是如何工作的?
列表和元组的本质区别是什么?
字典的键为什么必须是不可变的?
集合的底层实现是什么?
二、核心概念详解
2.1 数字类型
2.1.1 整数
python
# Python 整数没有大小限制
x = 10 ** 100
print(x) # 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
# 进制表示
binary = 0b1010 # 10
octal = 0o12 # 10
hexadecimal = 0xA # 10
# 进制转换
bin(10) # '0b1010'
oct(10) # '0o12'
hex(10) # '0xa'
# 整数运算
10 // 3 # 3(整除)
10 % 3 # 1(取余)
10 ** 3 # 1000(幂)
abs(-42) # 422.1.2 浮点数
python
# 浮点数
pi = 3.14159
e = 2.71828
# 科学计数法
avogadro = 6.022e23
electron_mass = 9.109e-31
# 精度问题
0.1 + 0.2 # 0.30000000000000004
abs(0.1 + 0.2 - 0.3) < 1e-10 # True
# 使用 decimal 模块进行精确计算
from decimal import Decimal
Decimal('0.1') + Decimal('0.2') # Decimal('0.3')
# 数学函数
import math
math.sqrt(16) # 4.0
math.floor(3.7) # 3
math.ceil(3.2) # 4
math.pi # 3.1415926535897932.1.3 复数
python
# 复数
z = 3 + 4j
z.real # 3.0
z.imag # 4.0
abs(z) # 5.0(模)
z.conjugate() # (3-4j)2.2 字符串深入
2.2.1 字符串切片
python
s = "Hello, World!"
# 基本切片
s[0:5] # "Hello"
s[7:] # "World!"
s[:5] # "Hello"
s[-6:] # "orld!"
s[::2] # "Hlo ol!"(步长为2)
s[::-1] # "!dlroW ,olleH"(反转)
# 切片不会修改原字符串
s[0:5] = "Hi" # TypeError: strings are immutable2.2.2 字符串格式化
python
name = "Alice"
age = 30
# % 格式化(旧式)
"Name: %s, Age: %d" % (name, age)
# str.format(Python 3)
"Name: {}, Age: {}".format(name, age)
"Name: {name}, Age: {age}".format(name=name, age=age)
# f-string(Python 3.6+,推荐)
f"Name: {name}, Age: {age}"
f"Next year: {age + 1}"
f"{'hello':>10}" # ' hello'(右对齐)
f"{'hello':<10}" # 'hello '(左对齐)
f"{'hello':^10}" # ' hello '(居中)
f"{3.14159:.2f}" # '3.14'
# 数字格式化
f"{1000000:,}" # '1,000,000'
f"{0.25:.1%}" # '25.0%'
f"{42:b}" # '101010'(二进制)
f"{255:x}" # 'ff'(十六进制)2.2.3 字符串编码
python
# Unicode 字符串
s = "Hello, 世界"
len(s) # 9(字符数)
s.encode('utf-8') # b'Hello, \xe4\xb8\x96\xe7\x95\x8c'(字节)
# 字节串
b = b'Hello'
b.decode('utf-8') # 'Hello'
# 字符编码
ord('A') # 65
chr(65) # 'A'
ord('中') # 20013
chr(20013) # '中'2.3 列表与元组
2.3.1 列表
python
# 列表(可变序列)
numbers = [1, 2, 3, 4, 5]
# 切片
numbers[1:3] # [2, 3]
numbers[::2] # [1, 3, 5]
numbers[::-1] # [5, 4, 3, 2, 1]
# 切片赋值(可以改变长度)
numbers[1:3] = [20, 30, 40]
# [1, 20, 30, 40, 4, 5]
numbers[1:1] = [10, 15] # 在位置1插入
# [1, 10, 15, 20, 30, 40, 4, 5]
numbers[1:3] = [] # 删除
# [1, 20, 30, 40, 4, 5]
# 列表方法
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort() # [1, 1, 2, 3, 4, 5, 6, 9]
numbers.sort(reverse=True) # [9, 6, 5, 4, 3, 2, 1, 1]
numbers.reverse() # 反转
numbers.index(5) # 查找位置
numbers.count(1) # 计数
# 列表推导式
squares = [x**2 for x in range(10)]
matrix = [[i*j for j in range(4)] for i in range(3)]2.3.2 元组
python
# 元组(不可变序列)
point = (3, 4)
rgb = (255, 128, 0)
# 元组解包
x, y = point
r, g, b = rgb
# 交换变量
a, b = 1, 2
a, b = b, a # a=2, b=1
# 命名元组
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
p.x # 3
p.y # 42.4 字典与集合
2.4.1 字典
python
# 字典操作
d = {"a": 1, "b": 2, "c": 3}
# 安全访问
d.get("a") # 1
d.get("d", 0) # 0(默认值)
d.setdefault("d", 4) # 4(不存在时设置)
# 合并字典(Python 3.9+)
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
d3 = d1 | d2 # {"a": 1, "b": 3, "c": 4}
# 字典视图
d.keys() # dict_keys(['a', 'b', 'c'])
d.values() # dict_values([1, 2, 3])
d.items() # dict_items([('a', 1), ('b', 2), ('c', 3)])
# 特殊字典
from collections import defaultdict, OrderedDict, Counter
# defaultdict
dd = defaultdict(list)
dd["fruits"].append("apple")
dd["fruits"].append("banana")
# {"fruits": ["apple", "banana"]}
# Counter
c = Counter("abracadabra")
# Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
c.most_common(3) # [('a', 5), ('b', 2), ('r', 2)]2.4.2 集合
python
# 集合
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}
# 集合运算
s1 | s2 # {1, 2, 3, 4, 5, 6}(并集)
s1 & s2 # {3, 4}(交集)
s1 - s2 # {1, 2}(差集)
s1 ^ s2 # {1, 2, 5, 6}(对称差集)
# 子集/超集
{1, 2} <= {1, 2, 3} # True(子集)
{1, 2, 3} >= {1, 2} # True(超集)
# 集合推导式
squares = {x**2 for x in range(10)}2.5 类型转换
python
# 数字转换
int(3.14) # 3
float(42) # 42.0
complex(3) # (3+0j)
# 字符串转换
str(42) # '42'
int("42") # 42
float("3.14") # 3.14
bool(0) # False
bool("") # False
# 序列转换
list("abc") # ['a', 'b', 'c']
tuple([1, 2, 3]) # (1, 2, 3)
set([1, 2, 2, 3]) # {1, 2, 3}
dict([("a", 1), ("b", 2)]) # {'a': 1, 'b': 2}三、实战案例
3.1 矩阵转置
python
def transpose(matrix):
return [list(row) for row in zip(*matrix)]
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
result = transpose(matrix)
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]3.2 文本分析
python
from collections import Counter
import re
def analyze_text(text):
words = re.findall(r'\b\w+\b', text.lower())
word_count = len(words)
unique_words = len(set(words))
most_common = Counter(words).most_common(5)
avg_word_length = sum(len(w) for w in words) / word_count if word_count else 0
return {
"total_words": word_count,
"unique_words": unique_words,
"most_common": most_common,
"avg_word_length": round(avg_word_length, 2)
}
text = """
Python is a versatile programming language.
Python is used in web development, data science, and AI.
Python is easy to learn and fun to use.
"""
result = analyze_text(text)
for key, value in result.items():
print(f"{key}: {value}")四、本章小结
第2章深入讲解了 Python 的内置类型:
数字:整数无大小限制,浮点数有精度问题,使用 Decimal 进行精确计算。
字符串:不可变序列,支持切片、格式化、编码转换。
列表:可变序列,支持切片赋值、推导式。
元组:不可变序列,支持解包、命名元组。
字典:键值对,支持 defaultdict、Counter 等特殊类型。
集合:无序不重复,支持集合运算。
理解这些类型的特性和操作,是写出高效 Python 代码的基础。
五、思考与练习
思考题
Python 的整数为什么没有溢出?底层是如何实现的?
列表和元组的性能差异在哪里?
字典的键为什么必须是不可变的?
集合的底层实现是什么?
切片操作的内存开销如何?
编程练习
实现矩阵乘法:使用列表推导式。
实现文本搜索引擎:统计词频,支持关键词搜索。
实现 LRU 缓存:使用 OrderedDict。