Python基础语法万字详解

Python 基础知识学习总结

本文总结了 Python 基础知识的核心内容,包括序列操作、可变与不可变类型、列表方法、列表推导式、元组、字符串方法等。


目录


一、序列的基本操作

Python 中的序列类型包括:字符串(str)、列表(list)、元组(tuple)。它们都支持以下通用操作:

1.1 序列合并(+ 操作符)

作用: 将两个相同类型的序列拼接成一个新序列。

python 复制代码
# 字符串
"Hello" + "World"  # "HelloWorld"

# 列表
[1, 2, 3] + [4, 5, 6]  # [1, 2, 3, 4, 5, 6]

# 元组
(1, 2) + (3, 4)  # (1, 2, 3, 4)

注意:

  • 只能合并相同类型的序列
  • 会创建新对象,不修改原序列
  • 不能混合类型:"hello" + [1, 2]

1.2 序列重复(* 操作符)

作用: 将序列重复指定次数。

python 复制代码
# 字符串
"Ha" * 3  # "HaHaHa"

# 列表
[1, 2] * 3  # [1, 2, 1, 2, 1, 2]

# 元组
(1,) * 4  # (1, 1, 1, 1)

实际应用:

python 复制代码
# 创建分隔线
print("-" * 50)

# 初始化列表
zeros = [0] * 10  # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

1.3 成员检查(in / not in)

作用: 判断元素是否在序列中。

python 复制代码
# 字符串
"o" in "Hello"  # True
"x" in "Hello"  # False

# 列表
3 in [1, 2, 3, 4]  # True
10 not in [1, 2, 3, 4]  # True

# 元组
"red" in ("red", "green", "blue")  # True

# 字典(检查键)
"name" in {"name": "Tom", "age": 20}  # True

1.4 序列比较(>, >=, ==, <, <=)

作用: 按字典序逐元素比较序列。

python 复制代码
# 字符串比较(按字典序)
"abc" < "abd"  # True
"apple" > "app"  # True

# 列表比较(逐元素比较)
[1, 2, 3] < [1, 2, 4]  # True
[1, 2] < [1, 2, 3]  # True

# 元组比较
(1, 2) < (1, 3)  # True

比较规则:

  1. 从第一个元素开始逐个比较
  2. 遇到不同的元素,比较结果即为序列比较结果
  3. 如果所有元素都相同,较短的序列更小

二、可变序列与不可变序列

2.1 核心概念

不可变序列: 创建后不能修改内容

  • 字符串(str)
  • 元组(tuple)
  • 数字(int, float)

可变序列: 创建后可以修改内容

  • 列表(list)
  • 字典(dict)
  • 集合(set)

2.2 不可变序列的特点

python 复制代码
# 字符串不可变
s = "hello"
s[0] = "H"  # ❌ TypeError

# 元组不可变
t = (1, 2, 3)
t[0] = 100  # ❌ TypeError

# 数字不可变
x = 10
x = x + 5  # 创建新对象,不是修改原对象

"修改"不可变对象时发生了什么?

python 复制代码
s = "hello"
print(id(s))  # 地址1

s = s + " world"
print(id(s))  # 地址2(变了!)

实际上是创建了新对象,变量指向了新对象。

2.3 可变序列的特点

python 复制代码
# 列表可变
lst = [1, 2, 3]
print(id(lst))  # 地址1

lst[0] = 100
lst.append(4)
print(id(lst))  # 地址1(没变!)

修改操作在原对象上进行,内存地址不变。

2.4 特殊情况:元组中的可变对象

python 复制代码
# 元组本身不可变
t = (1, 2, [3, 4])
t[0] = 100  # ❌ 不能修改元组

# 但元组中的列表可以修改
t[2].append(5)
print(t)  # (1, 2, [3, 4, 5])

理解: 元组存储的是引用(指针),引用不能变,但引用指向的可变对象可以变。

2.5 可变 vs 不可变对比

特性 可变序列 不可变序列
修改 可以原地修改 不能修改,只能创建新对象
内存地址 修改后地址不变 "修改"后地址改变
性能 修改效率高 每次"修改"都创建新对象
作为字典键 不可以 可以
线程安全 需要加锁 天然线程安全
典型类型 list, dict, set str, tuple, int, float

2.6 使用场景

使用不可变序列:

  • 需要保护数据不被修改
  • 作为字典的键
  • 配置信息
  • 函数返回多个值

使用可变序列:

  • 需要频繁修改数据
  • 动态数据收集
  • 缓存和查找

三、列表的常用方法

列表是 Python 中最常用的可变序列,提供了丰富的方法。

3.1 添加元素

append(元素) - 尾部添加
python 复制代码
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits)  # ["apple", "banana", "orange"]
  • 返回 None
  • 直接修改原列表
insert(位置, 元素) - 指定位置插入
python 复制代码
colors = ["red", "blue"]
colors.insert(1, "green")
print(colors)  # ["red", "green", "blue"]
extend(序列) - 批量添加
python 复制代码
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)  # [1, 2, 3, 4, 5, 6]

extend vs append:

python 复制代码
a = [1, 2]
b = [1, 2]

a.extend([3, 4])  # [1, 2, 3, 4] - 拆开添加
b.append([3, 4])  # [1, 2, [3, 4]] - 整体添加

3.2 删除元素

pop(下标) - 删除并返回
python 复制代码
stack = [1, 2, 3, 4, 5]
last = stack.pop()  # 删除最后一个
print(last)  # 5
print(stack)  # [1, 2, 3, 4]

first = stack.pop(0)  # 删除第一个
print(first)  # 1
remove(元素) - 删除指定元素
python 复制代码
numbers = [1, 2, 3, 2, 4]
numbers.remove(2)  # 只删除第一个2
print(numbers)  # [1, 3, 2, 4]
  • 只删除第一个匹配的元素
  • 元素不存在会报错
clear() - 清空列表
python 复制代码
items = [1, 2, 3]
items.clear()
print(items)  # []

3.3 查找元素

index(元素, 起始, 终止) - 查找索引
python 复制代码
fruits = ["apple", "banana", "cherry", "banana"]
idx = fruits.index("banana")  # 1(第一个banana)
idx2 = fruits.index("banana", 2)  # 3(从索引2开始找)
  • 找不到会报错
  • 只返回第一个匹配的索引
count(元素) - 统计个数
python 复制代码
numbers = [1, 2, 2, 3, 2, 4]
count = numbers.count(2)  # 3

3.4 排序和反转

sort(key, reverse) - 原地排序
python 复制代码
numbers = [3, 1, 4, 1, 5, 9]
numbers.sort()  # 升序
print(numbers)  # [1, 1, 3, 4, 5, 9]

numbers.sort(reverse=True)  # 降序
print(numbers)  # [9, 5, 4, 3, 1, 1]

# 自定义排序
words = ["python", "java", "c", "javascript"]
words.sort(key=len)  # 按长度排序
print(words)  # ["c", "java", "python", "javascript"]

sort() vs sorted():

python 复制代码
list1 = [3, 1, 2]
list1.sort()  # 原地排序,返回None

list2 = [3, 1, 2]
result = sorted(list2)  # 返回新列表,原列表不变
reverse() - 反转列表
python 复制代码
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers)  # [5, 4, 3, 2, 1]

3.5 拷贝列表

copy() - 浅拷贝
python 复制代码
original = [1, 2, 3]
copied = original.copy()

copied.append(4)
print(original)  # [1, 2, 3] - 不受影响
print(copied)    # [1, 2, 3, 4]

浅拷贝的陷阱:

python 复制代码
nested = [1, 2, [3, 4]]
shallow = nested.copy()

shallow[2].append(5)
print(nested)  # [1, 2, [3, 4, 5]] - 也被修改了!

解决方法:深拷贝

python 复制代码
import copy
deep = copy.deepcopy(nested)
deep[2].append(6)
print(nested)  # [1, 2, [3, 4, 5]] - 不受影响

四、列表推导式

列表推导式是 Python 中创建列表的简洁优雅方式。

4.1 基本语法

python 复制代码
# 传统方式
squares = []
for i in range(10):
    squares.append(i ** 2)

# 列表推导式
squares = [i ** 2 for i in range(10)]

语法结构:

python 复制代码
[表达式 for 变量 in 可迭代对象]

4.2 带条件筛选

python 复制代码
# 筛选偶数
evens = [i for i in range(20) if i % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# 筛选长单词
words = ["hi", "hello", "python", "code"]
long_words = [word for word in words if len(word) > 4]
# ["hello", "python"]

语法结构:

python 复制代码
[表达式 for 变量 in 可迭代对象 if 条件]

4.3 if-else 表达式

python 复制代码
# 偶数变0,奇数保持
result = [0 if i % 2 == 0 else i for i in range(10)]
# [0, 1, 0, 3, 0, 5, 0, 7, 0, 9]

# 标记奇偶
labels = ["偶数" if i % 2 == 0 else "奇数" for i in range(6)]
# ["偶数", "奇数", "偶数", "奇数", "偶数", "奇数"]

语法结构:

python 复制代码
[表达式1 if 条件 else 表达式2 for 变量 in 可迭代对象]

注意: if-else 在 for 前面,单独的 if 在 for 后面。

4.4 嵌套列表推导式

python 复制代码
# 二维列表展平
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [item for row in matrix for item in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 笛卡尔积
colors = ["红", "蓝"]
sizes = ["S", "M", "L"]
combinations = [(color, size) for color in colors for size in sizes]
# [("红", "S"), ("红", "M"), ("红", "L"), ("蓝", "S"), ("蓝", "M"), ("蓝", "L")]

4.5 实际应用

数据清洗:

python 复制代码
raw_data = ["  Hello  ", "WORLD", "  Python  "]
cleaned = [item.strip().lower() for item in raw_data]
# ["hello", "world", "python"]

提取字段:

python 复制代码
users = [
    {"name": "Tom", "age": 20},
    {"name": "Jerry", "age": 22}
]
names = [user["name"] for user in users]
# ["Tom", "Jerry"]

数据转换:

python 复制代码
celsius = [0, 10, 20, 30]
fahrenheit = [c * 9/5 + 32 for c in celsius]
# [32.0, 50.0, 68.0, 86.0]

4.6 其他推导式

集合推导式:

python 复制代码
numbers = [1, 2, 2, 3, 3, 3]
unique = {n ** 2 for n in numbers}
# {1, 4, 9} - 自动去重

字典推导式:

python 复制代码
squares = {i: i ** 2 for i in range(1, 6)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

生成器表达式:

python 复制代码
gen = (i ** 2 for i in range(5))
# 用圆括号,返回生成器,节省内存

五、元组详解

元组是 Python 中的不可变序列,类似"只读版本的列表"。

5.1 元组的创建

python 复制代码
# 使用圆括号
tuple1 = (1, 2, 3)

# 不使用括号
tuple2 = 1, 2, 3

# 单元素元组(必须有逗号!)
not_tuple = (5)    # 这是 int 5
is_tuple = (5,)    # 这才是元组

# 空元组
empty = ()

# 从其他序列转换
from_list = tuple([1, 2, 3])
from_string = tuple("hello")  # ('h', 'e', 'l', 'l', 'o')

重要: 单元素元组必须有逗号!

5.2 元组的访问

python 复制代码
fruits = ("apple", "banana", "cherry")

# 索引访问
print(fruits[0])   # "apple"
print(fruits[-1])  # "cherry"

# 切片
print(fruits[:2])  # ("apple", "banana")
print(fruits[::-1])  # ("cherry", "banana", "apple")

5.3 元组的方法(只有2个)

python 复制代码
numbers = (1, 2, 2, 3, 2, 4)

# count() - 统计元素个数
count = numbers.count(2)  # 3

# index() - 查找元素索引
idx = numbers.index(3)  # 3

5.4 元组解包(重要!)

基本解包:

python 复制代码
point = (10, 20)
x, y = point
print(x, y)  # 10 20

交换变量:

python 复制代码
a, b = 10, 20
a, b = b, a  # 优雅的交换
print(a, b)  # 20 10

使用 * 收集剩余元素:

python 复制代码
numbers = (1, 2, 3, 4, 5)

first, *rest = numbers
# first=1, rest=[2, 3, 4, 5]

first, *middle, last = numbers
# first=1, middle=[2, 3, 4], last=5

*beginning, last = numbers
# beginning=[1, 2, 3, 4], last=5

忽略不需要的值:

python 复制代码
person = ("Tom", 25, "Beijing", "Engineer")
name, _, city, _ = person
# 只要 name 和 city

函数返回多个值:

python 复制代码
def get_user_info():
    return "Alice", 30, "Shanghai"

name, age, city = get_user_info()

5.5 元组 vs 列表

特性 元组 列表
定义符号 () []
可变性 不可变 可变
速度 更快 较慢
内存 更少 更多
方法数量 2个 11个
作为字典键 可以 不可以

5.6 元组的使用场景

1. 函数返回多个值:

python 复制代码
def calculate(a, b):
    return a + b, a - b, a * b, a / b

add, sub, mul, div = calculate(10, 2)

2. 作为字典的键:

python 复制代码
locations = {
    (0, 0): "起点",
    (1, 0): "右边",
    (0, 1): "上边"
}

3. 表示坐标:

python 复制代码
point_2d = (10, 20)
point_3d = (10, 20, 30)

4. 配置信息:

python 复制代码
DATABASE_CONFIG = ("localhost", 3306, "mydb", "utf8")

5. RGB 颜色:

python 复制代码
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

5.7 命名元组

python 复制代码
from collections import namedtuple

# 定义类型
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)

# 可以用索引访问
print(p[0])  # 10

# 也可以用名字访问(更清晰)
print(p.x)   # 10
print(p.y)   # 20

六、字符串常用方法

字符串是 Python 中的不可变序列,提供了丰富的文本处理方法。

6.1 判断类方法(is... 系列)

python 复制代码
# isascii() - 是否都是 ASCII 字符
"Hello123".isascii()  # True
"你好".isascii()      # False

# isalnum() - 是否都是字母或数字
"Hello123".isalnum()  # True
"Hello 123".isalnum() # False(有空格)

# isdigit() - 是否都是数字
"12345".isdigit()     # True
"123.45".isdigit()    # False(有小数点)

# isalpha() - 是否都是字母
"Hello".isalpha()     # True
"Hello123".isalpha()  # False

# islower() / isupper() - 是否都是小写/大写
"hello".islower()     # True
"HELLO".isupper()     # True

实际应用:验证用户名

python 复制代码
username = "user123"
if username.isalnum() and 6 <= len(username) <= 20:
    print("用户名有效")

6.2 大小写转换

python 复制代码
s = "Hello World"

# capitalize() - 首字母大写
s.capitalize()  # "Hello world"

# upper() - 全部大写
s.upper()  # "HELLO WORLD"

# lower() - 全部小写
s.lower()  # "hello world"

实际应用:不区分大小写的比较

python 复制代码
user_input = "PYTHON"
keyword = "python"

if user_input.lower() == keyword.lower():
    print("匹配成功")

6.3 格式化和填充

python 复制代码
# center(长度, 填充字符) - 居中对齐
"Python".center(20, "*")  # "*******Python*******"

# 制作标题
title = "欢迎使用系统"
print(title.center(40, "="))
# ================欢迎使用系统================

6.4 查找和统计

python 复制代码
s = "hello world, hello python"

# count(子串) - 统计出现次数
s.count("hello")  # 2
s.count("o")      # 4

# find(子串) - 查找位置(找不到返回-1)
s.find("world")   # 6
s.find("java")    # -1

# index(子串) - 查找位置(找不到报错)
s.index("world")  # 6
s.index("java")   # ValueError

find() vs index():

  • find() 找不到返回 -1,不报错
  • index() 找不到抛出异常

6.5 判断开头和结尾

python 复制代码
s = "hello world"

# startswith() - 判断开头
s.startswith("hello")  # True
s.startswith("world")  # False

# endswith() - 判断结尾
s.endswith("world")    # True
s.endswith("hello")    # False

实际应用:筛选文件

python 复制代码
files = ["test.py", "data.txt", "main.py"]
py_files = [f for f in files if f.endswith(".py")]
# ["test.py", "main.py"]

# 检查多个后缀
filename = "image.jpg"
if filename.endswith((".jpg", ".png", ".gif")):
    print("这是图片文件")

6.6 拼接和分割

join() - 用分隔符连接序列
python 复制代码
words = ["hello", "world", "python"]

" ".join(words)   # "hello world python"
"-".join(words)   # "hello-world-python"
", ".join(words)  # "hello, world, python"

# 连接字符串中的每个字符
"-".join("Python")  # "P-y-t-h-o-n"

实际应用:构建 URL

python 复制代码
parts = ["https:", "", "www.example.com", "api", "users"]
url = "/".join(parts)
# "https://www.example.com/api/users"
split() - 拆分字符串
python 复制代码
s = "hello world python"
s.split()  # ["hello", "world", "python"](默认按空格)

s = "apple,banana,cherry"
s.split(",")  # ["apple", "banana", "cherry"]

s = "a-b-c-d-e"
s.split("-", 2)  # ["a", "b", "c-d-e"](只拆2次)

实际应用:解析 CSV

python 复制代码
csv_line = "Tom,20,Beijing"
name, age, city = csv_line.split(",")

join() 和 split() 是互逆操作:

python 复制代码
original = "hello world python"
words = original.split()        # 拆分
restored = " ".join(words)      # 重新连接
original == restored  # True

6.7 替换

python 复制代码
s = "hello world, hello python"

# replace(旧串, 新串) - 替换所有
s.replace("hello", "hi")
# "hi world, hi python"

# replace(旧串, 新串, 次数) - 只替换指定次数
s.replace("hello", "hi", 1)
# "hi world, hello python"

# 删除字符(替换为空)
s.replace(" ", "")
# "helloworld,hellopython"

实际应用:数据清洗

python 复制代码
phone = "138-1234-5678"
clean = phone.replace("-", "")
# "13812345678"

链式替换:

python 复制代码
s = "hello world"
result = s.replace("hello", "hi").replace("world", "python")
# "hi python"

6.8 综合应用

验证密码强度:

python 复制代码
def check_password(pwd):
    if len(pwd) < 8:
        return False, "长度至少8位"
    
    has_upper = any(c.isupper() for c in pwd)
    has_lower = any(c.islower() for c in pwd)
    has_digit = any(c.isdigit() for c in pwd)
    
    if has_upper and has_lower and has_digit:
        return True, "密码强度良好"
    return False, "需要包含大小写字母和数字"

格式化电话号码:

python 复制代码
def format_phone(phone):
    digits = "".join(c for c in phone if c.isdigit())
    if len(digits) == 11:
        return f"{digits[:3]}-{digits[3:7]}-{digits[7:]}"
    return "无效"

format_phone("13812345678")  # "138-1234-5678"

生成缩写:

python 复制代码
def create_abbreviation(phrase):
    words = phrase.split()
    return "".join(word[0].upper() for word in words)

create_abbreviation("Hypertext Markup Language")  # "HTML"

七、总结与对比

7.1 序列类型对比表

特性 字符串 列表 元组
定义符号 ""'' [] ()
可变性 不可变 可变 不可变
元素类型 只能是字符 任意类型 任意类型
方法数量 40+ 11 2
作为字典键 可以 不可以 可以
性能 中等 最快
使用场景 文本处理 动态数据 固定数据

7.2 核心概念总结

不可变的本质
python 复制代码
# 不可变对象"修改"时创建新对象
s = "hello"
s = s + " world"  # 创建新字符串

# 可变对象修改时在原对象上操作
lst = [1, 2, 3]
lst.append(4)  # 原地修改
方法返回值规律

修改类方法:

  • 可变对象:返回 None,原地修改
  • 不可变对象:返回新对象,原对象不变
python 复制代码
# 列表方法返回 None
lst = [1, 2, 3]
result = lst.append(4)  # result 是 None

# 字符串方法返回新字符串
s = "hello"
result = s.upper()  # result 是 "HELLO"

查询类方法:

  • 返回查询结果(数字、布尔值等)
python 复制代码
lst.count(2)      # 返回数字
s.startswith("h") # 返回布尔值

7.3 常用操作速查表

列表常用操作
python 复制代码
# 添加
lst.append(x)        # 尾部添加
lst.insert(i, x)     # 指定位置插入
lst.extend(seq)      # 批量添加

# 删除
lst.pop()            # 删除并返回最后一个
lst.remove(x)        # 删除指定元素
lst.clear()          # 清空

# 查找
lst.index(x)         # 查找索引
lst.count(x)         # 统计个数

# 排序
lst.sort()           # 原地排序
lst.reverse()        # 反转

# 拷贝
lst.copy()           # 浅拷贝
字符串常用操作
python 复制代码
# 判断
s.isdigit()          # 是否都是数字
s.isalpha()          # 是否都是字母
s.isalnum()          # 是否都是字母或数字
s.islower()          # 是否都是小写
s.isupper()          # 是否都是大写

# 转换
s.upper()            # 转大写
s.lower()            # 转小写
s.capitalize()       # 首字母大写

# 查找
s.find(sub)          # 查找位置(返回-1)
s.index(sub)         # 查找位置(报错)
s.count(sub)         # 统计次数

# 判断位置
s.startswith(sub)    # 是否以...开头
s.endswith(sub)      # 是否以...结尾

# 拆分合并
s.split(sep)         # 拆分
sep.join(seq)        # 合并

# 替换
s.replace(old, new)  # 替换
元组常用操作
python 复制代码
# 创建
t = (1, 2, 3)
t = 1, 2, 3
t = (1,)             # 单元素元组

# 查询
t.count(x)           # 统计个数
t.index(x)           # 查找索引

# 解包
x, y = (1, 2)
first, *rest = (1, 2, 3, 4)

7.4 最佳实践

选择合适的数据类型

使用列表:

  • 需要频繁修改数据
  • 数据量动态变化
  • 需要排序、插入、删除操作
python 复制代码
# 动态收集数据
results = []
for test in tests:
    results.append(run_test(test))

使用元组:

  • 数据不应该被修改
  • 作为字典的键
  • 函数返回多个值
  • 表示固定的数据结构
python 复制代码
# 配置信息
DB_CONFIG = ("localhost", 3306, "mydb")

# 函数返回多个值
def get_stats(data):
    return min(data), max(data), sum(data)/len(data)

使用字符串:

  • 文本处理
  • 数据验证
  • 格式化输出
python 复制代码
# 数据验证
if username.isalnum() and len(username) >= 6:
    print("有效")
性能优化建议

1. 字符串拼接:

python 复制代码
# ❌ 慢:多次创建新对象
result = ""
for word in words:
    result = result + word

# ✓ 快:使用 join
result = "".join(words)

2. 列表初始化:

python 复制代码
# ❌ 慢:多次 append
lst = []
for i in range(1000):
    lst.append(i)

# ✓ 快:列表推导式
lst = [i for i in range(1000)]

# ✓ 更快:直接转换
lst = list(range(1000))

3. 成员检查:

python 复制代码
# ❌ 慢:列表查找 O(n)
if item in my_list:
    pass

# ✓ 快:集合查找 O(1)
my_set = set(my_list)
if item in my_set:
    pass
常见陷阱

1. 可变对象作为默认参数:

python 复制代码
# ❌ 错误
def add_item(item, items=[]):
    items.append(item)
    return items

# 多次调用会共享同一个列表!

# ✓ 正确
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

2. 浅拷贝陷阱:

python 复制代码
# ❌ 问题
original = [1, 2, [3, 4]]
copy = original.copy()
copy[2].append(5)
# original 也被修改了!

# ✓ 解决
import copy
deep_copy = copy.deepcopy(original)

3. 单元素元组忘记逗号:

python 复制代码
# ❌ 错误:这是 int
t = (5)

# ✓ 正确:这是 tuple
t = (5,)

4. 字符串方法忘记接收返回值:

python 复制代码
# ❌ 错误
s = "hello"
s.upper()  # 没有接收返回值
print(s)   # 还是 "hello"

# ✓ 正确
s = s.upper()
print(s)   # "HELLO"

7.5 实战技巧

技巧1:链式调用
python 复制代码
# 字符串处理
text = "  Hello World  "
result = text.strip().lower().replace(" ", "_")
# "hello_world"

# 列表操作
data = [3, 1, 4, 1, 5, 9, 2, 6]
result = sorted(data)[:5]  # 取前5个最小值
技巧2:解包技巧
python 复制代码
# 交换变量
a, b = b, a

# 收集剩余元素
first, *rest, last = [1, 2, 3, 4, 5]

# 忽略不需要的值
name, _, _, city = ("Tom", 20, "Male", "Beijing")
技巧3:列表推导式
python 复制代码
# 数据转换
squares = [x**2 for x in range(10)]

# 数据筛选
evens = [x for x in range(20) if x % 2 == 0]

# 数据清洗
cleaned = [s.strip().lower() for s in raw_data]

# 提取字段
names = [user["name"] for user in users]
技巧4:字符串格式化
python 复制代码
# f-string(推荐)
name = "Tom"
age = 20
print(f"{name} is {age} years old")

# format()
print("{} is {} years old".format(name, age))

# % 格式化(旧式)
print("%s is %d years old" % (name, age))
技巧5:多行字符串
python 复制代码
# 三引号
text = """
这是一段
多行文本
"""

# 括号自动连接
text = (
    "这是第一行"
    "这是第二行"
    "这是第三行"
)

八、学习建议

8.1 记忆技巧

1. 方法分类记忆:

  • 判断类(is...)→ 返回布尔值
  • 转换类(upper, lower)→ 返回新对象
  • 查找类(find, index, count)→ 返回数字
  • 修改类(append, remove)→ 返回 None

2. 对比记忆:

  • find() vs index() - 找不到的处理不同
  • append() vs extend() - 添加方式不同
  • sort() vs sorted() - 是否原地修改
  • copy() vs deepcopy() - 拷贝深度不同

3. 实践记忆:

  • 多写代码,在实际应用中记忆
  • 遇到问题时查文档,加深印象

8.2 进阶方向

1. 深入理解:

  • 内存管理和引用
  • 迭代器和生成器
  • 装饰器和闭包

2. 标准库:

  • collections(高级数据结构)
  • itertools(迭代工具)
  • functools(函数工具)

3. 性能优化:

  • 时间复杂度分析
  • 内存优化技巧
  • 使用 timeit 测试性能

8.3 推荐资源

官方文档:

在线练习:

  • LeetCode(算法练习)
  • HackerRank(编程挑战)
  • Codewars(代码练习)

书籍推荐:

  • 《Python 编程:从入门到实践》
  • 《流畅的 Python》
  • 《Effective Python》

相关推荐
alonewolf_991 天前
Spring IOC容器扩展点全景:深入探索与实践演练
java·后端·spring
super_lzb1 天前
springboot打war包时将外部配置文件打入到war包内
java·spring boot·后端·maven
毛小茛1 天前
芋道管理系统学习——项目结构
java·学习
阿里嘎多学长1 天前
2026-01-02 GitHub 热点项目精选
开发语言·程序员·github·代码托管
天远云服1 天前
Go语言高并发实战:集成天远手机号码归属地核验API打造高性能风控中台
大数据·开发语言·后端·golang
东北小狐狸-Hellxz1 天前
解决java客户端连接ssh失败问题
java·网络·ssh
悟能不能悟1 天前
HttpServletRequest request获取整个headers有什么方法
java
__万波__1 天前
二十三种设计模式(二十)--解释器模式
java·设计模式·解释器模式
网安_秋刀鱼1 天前
【java安全】反序列化 - CC1链
java·c语言·安全