# 定义函数
def greet(name):
"""一个简单的问候函数"""
return f"Hello, {name}!"
# 调用函数
result = greet("Alice")
print(result) # 输出: Hello, Alice!
# 带默认参数的函数
def power(base, exponent=2):
"""计算幂次,默认平方"""
return base ** exponent
print(power(3)) # 输出: 9
print(power(3, 3)) # 输出: 27
# 位置参数
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
# 关键字参数(调用时指定参数名)
describe_pet(pet_name="Tom", animal_type="cat")
# 任意数量的位置参数(*args)
def make_pizza(*toppings):
"""打印所有配料"""
print("Making pizza with:")
for topping in toppings:
print(f"- {topping}")
make_pizza('mushrooms', 'green peppers', 'extra cheese')
# 任意数量的关键字参数(**kwargs)
def build_profile(first, last, **user_info):
"""创建用户信息字典"""
profile = {'first_name': first, 'last_name': last}
profile.update(user_info)
return profile
user_profile = build_profile('John', 'Doe', age=30, location='New York')
print(user_profile)
# 返回多个值(实际返回元组)
def get_name():
first = "John"
last = "Doe"
return first, last # 返回元组
# 接收多个返回值
first_name, last_name = get_name()
# 函数作为参数
def apply_operation(func, x, y):
return func(x, y)
def add(a, b):
return a + b
result = apply_operation(add, 5, 3) # 输出: 8
# 创建列表
fruits = ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# 访问元素
print(fruits[0]) # 输出: apple
print(fruits[-1]) # 输出: cherry(倒数第一个)
print(fruits[1:3]) # 输出: ['banana', 'cherry'](切片)
# 添加元素
fruits.append('orange') # 末尾添加
fruits.insert(1, 'mango') # 指定位置插入
fruits.extend(['grape', 'kiwi']) # 合并列表
# 删除元素
fruits.remove('banana') # 按值删除
popped = fruits.pop() # 删除并返回最后一个元素
popped = fruits.pop(1) # 删除指定位置元素
del fruits[0] # 删除指定位置
# 其他操作
fruits.sort() # 排序(原地修改)
sorted_fruits = sorted(fruits) # 返回新列表
fruits.reverse() # 反转
count = fruits.count('apple') # 计数
index = fruits.index('cherry') # 查找索引
# 基本列表推导式
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件的列表推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]
# 多重循环
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]]
flattened = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 列表复制
original = [1, 2, 3]
shallow_copy = original.copy() # 浅拷贝
deep_copy = original[:] # 另一种浅拷贝方式
# 嵌套列表的深拷贝
import copy
nested = [[1, 2], [3, 4]]
deep_copy_nested = copy.deepcopy(nested)
# 列表解包
first, *middle, last = [1, 2, 3, 4, 5]
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
# 创建元组
coordinates = (10, 20)
single_element = (42,) # 注意逗号(避免与括号表达式混淆)
empty_tuple = ()
# 访问元素(与列表类似)
print(coordinates[0]) # 10
print(coordinates[-1]) # 20
# 元组解包
x, y = coordinates
print(f"x={x}, y={y}") # x=10, y=20
# 交换变量值(利用元组解包)
a, b = 5, 10
a, b = b, a # a=10, b=5
# 元组是不可变的
t = (1, 2, 3)
# t[0] = 10 # 错误!不能修改元组元素
# 但可以重新赋值整个元组
t = (4, 5, 6)
# 元组可以包含可变对象
mixed_tuple = ([1, 2], 3, 4)
mixed_tuple[0].append(3) # 可以修改列表内容
# mixed_tuple[1] = 5 # 错误!不能修改元组元素
# 元组比列表更高效(内存占用小,访问速度快)
# 传递列表到函数
def process_numbers(numbers):
"""处理数字列表"""
total = sum(numbers)
average = total / len(numbers)
return total, average, max(numbers), min(numbers)
# 使用元组返回多个值
scores = [85, 90, 78, 92, 88]
total, avg, highest, lowest = process_numbers(scores)
# 函数返回列表
def get_even_numbers(limit):
"""返回指定范围内的偶数列表"""
return [x for x in range(limit) if x % 2 == 0]
# 函数返回元组(通常用于多个返回值)
def get_min_max(numbers):
return min(numbers), max(numbers)
# 使用*解包列表/元组作为参数
def connect_to_db(host, port, user, password):
print(f"Connecting to {user}@{host}:{port}")
params = ['localhost', 3306, 'admin', 'secret']
connect_to_db(*params) # 解包列表作为位置参数
# 使用**解包字典作为关键字参数
config = {'host': 'localhost', 'port': 3306, 'user': 'admin', 'password': 'secret'}
connect_to_db(**config) # 解包字典作为关键字参数
# 学生成绩管理系统
def calculate_statistics(scores):
"""计算统计信息"""
total = sum(scores)
average = total / len(scores)
sorted_scores = sorted(scores)
# 中位数
n = len(sorted_scores)
if n % 2 == 0:
median = (sorted_scores[n//2-1] + sorted_scores[n//2]) / 2
else:
median = sorted_scores[n//2]
# 返回元组
return (total, average, median, max(scores), min(scores))
# 使用示例
student_scores = [85, 92, 78, 90, 88, 95, 79]
stats = calculate_statistics(student_scores)
print(f"总分: {stats[0]}, 平均分: {stats[1]:.2f}, 中位数: {stats[2]}")
# 使用字典包装更清晰
stat_names = ['total', 'average', 'median', 'highest', 'lowest']
result_dict = dict(zip(stat_names, stats))
# 相互转换
my_list = [1, 2, 3, 4]
my_tuple = tuple(my_list) # 列表转元组
new_list = list(my_tuple) # 元组转列表
# 在实际中的应用
def safe_function(data):
"""接收数据,确保不修改原始数据"""
# 将输入转换为元组(防止意外修改)
data_tuple = tuple(data) if isinstance(data, list) else data
# 处理数据...
processed = [x * 2 for x in data_tuple]
# 返回新列表(不修改输入)
return processed
函数设计原则:
列表vs元组选择:
性能考虑:
代码可读性:
这个指南涵盖了Python中函数、列表和元组的核心用法,掌握了这些基础知识,你就可以开始编写实用的Python程序了。建议多动手实践,通过实际项目加深理解。