Python 入门必吃透:函数、列表与元组核心用法
Python 的函数、列表和元组是初学者必须彻底掌握的三大核心概念。它们几乎出现在每一个 Python 程序中,理解透彻能让你写出更简洁、高效、可读性强的代码。下面从基础语法到进阶用法,一步步带你吃透它们。
1. 列表(List)——可变序列的王者
列表是 Python 中最常用、最灵活的序列类型,用方括号 [] 定义,支持存储任意类型的数据,且可变(可以增删改)。
# 创建列表
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
# 常用操作
fruits.append("orange") # 添加元素到末尾 → ['apple', 'banana', 'cherry', 'orange']
fruits.insert(1, "grape") # 在索引1位置插入 → ['apple', 'grape', 'banana', ...]
fruits.remove("banana") # 删除第一个匹配的元素
popped = fruits.pop() # 删除并返回末尾元素 → 'orange'
popped = fruits.pop(0) # 删除并返回索引0的元素 → 'apple'
# 切片操作(超级强大!)
print(fruits[1:4]) # 从索引1到3 → ['grape', 'banana', 'cherry']
print(fruits[:3]) # 前3个
print(fruits[2:]) # 从第2个到最后
print(fruits[::-1]) # 反转列表
# 修改元素
fruits[0] = "watermelon"
# 列表推导式(优雅又高效)
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, ..., 81]
evens = [x for x in range(20) if x % 2 == 0] # 所有偶数
关键点:
- 列表是可变的,适合需要频繁增删改的场景。
- 支持负索引:
fruits[-1]表示最后一个元素。 - 列表可以嵌套:
matrix = [[1,2], [3,4], [5,6]]
2. 元组(Tuple)——不可变的轻量级序列
元组用圆括号 () 定义,创建后不可修改,比列表更轻量、更安全,常用于固定数据。
# 创建元组
point = (3, 4)
colors = ("red", "green", "blue")
single = (42,) # 只有一个元素时必须加逗号!
empty = ()
# 访问同列表
print(point[0]) # 3
print(colors[1:]) # ('green', 'blue')
# 解包(元组最强大用法之一!)
x, y = point # x=3, y=4
a, b, c = colors # a="red", b="green", c="blue"
# 交换变量(Python 独有优雅写法)
a, b = b, a
# 函数返回多个值(实际上返回的是元组)
def get_user_info():
return "Alice", 25, "Beijing"
name, age, city = get_user_info()
关键点:
- 元组不可变 → 可作为字典的 key(列表不行!)
- 元组比列表占用内存更少,访问速度更快
- 单元素元组必须写逗号:
(42,)而不是(42)
3. 函数(Function)——代码复用的基石
函数是组织代码、提高可读性和复用性的核心工具。
# 基本定义
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
# 带返回值
def add(a, b):
return a + b
result = add(3, 5) # 8
# 默认参数(注意:默认参数只求值一次!)
def say_hello(name="World"):
print(f"Hello, {name}!")
say_hello() # Hello, World!
say_hello("Bob") # Hello, Bob!
# 可变参数
def sum_all(*args): # args 是元组
return sum(args)
print(sum_all(1, 2, 3, 4, 5)) # 15
def print_info(**kwargs): # kwargs 是字典
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="Beijing")
# 结合使用
def complex_func(a, b, *args, option="default", **kwargs):
print(a, b, args, option, kwargs)
complex_func(1, 2, 3, 4, x=10, y=20, option="custom")
关键点:
- 参数顺序:位置参数 →
*args→ 关键字参数 →**kwargs - 函数是一等公民:可以赋值、作为参数传递
- 匿名函数(lambda):
squares = list(map(lambda x: x**2, range(10)))
4. 三者结合的实战示例
# 统计学生成绩
students = [
("Alice", [88, 92, 85]),
("Bob", [76, 81, 89]),
("Charlie", [95, 90, 93])
]
def calculate_average(scores):
return sum(scores) / len(scores)
# 使用列表推导式 + 元组解包 + 函数
result = sorted(
[(name, round(calculate_average(scores), 2)) for name, scores in students],
key=lambda x: x[1],
reverse=True
)
print(result)
# [('Charlie', 92.67), ('Alice', 88.33), ('Bob', 82.0)]
5. 总结对比表
| 特性 | 列表 [ ] | 元组 ( ) | 函数 def / lambda |
|---|---|---|---|
| 可变性 | 可变 | 不可变 | – |
| 定义符号 | [] | () | def 或 lambda |
| 性能 | 稍慢(可变开销) | 更快、更省内存 | – |
| 典型用途 | 动态集合、栈/队列 | 固定数据、字典 key、返回多值 | 代码复用、逻辑封装 |
| 是否可哈希 | 不可(不能做 dict key) | 可 | – |
| 支持推导式 | 支持 | 支持(生成器表达式更常见) | – |
结语
- 列表:需要修改数据时用。
- 元组:数据固定不变、需要作为 key 或追求性能时用。
- 函数:任何重复逻辑都要封装成函数,结合默认参数、可变参数写出灵活接口。
真正吃透这三者,你就迈入了 Python 中级玩家的行列。建议多动手练习,尤其是列表推导式、元组解包和函数参数组合,它们是 Python 代码优雅的灵魂!
下一步可以学习:字典、集合、生成器、装饰器——继续加油!🚀