Python 序列遍历与推导式
列表推导式
通过简明语法创建新列表。
numbers = [1, 2, 3, 4, 5]
squared = [num * num for num in numbers]
print(squared)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)
字典遍历
访问字典的键值对。
user_data = {
"name": "sumingcheng",
"age": 25,
"city": "Beijing"
}
def print_user_info(data):
for key, value in data.items():
print(f"{key} {value}")
def get_filtered_items(data, exclude_keys):
return {k: v for k, v in data.items() if k not in exclude_keys}
序列索引遍历
使用 enumerate 获取序列的索引和值。
def process_items_with_index(items):
for index, item in enumerate(items):
print(f"处理第{index + 1}个项目 {item}")
tasks = ["任务1", "任务2", "任务3"]
process_items_with_index(tasks)
多序列并行遍历
使用 zip 同时遍历多个序列。
def combine_lists(names, ages, cities):
user_profiles = []
for name, age, city in zip(names, ages, cities):
profile = {
"name": name,
"age": age,
"city": city
}
user_profiles.append(profile)
return user_profiles
序列排序遍历
按特定顺序遍历序列。
def process_sorted_data(data, reverse=False):
for item in sorted(data, reverse=reverse):
yield item
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
for num in process_sorted_data(numbers):
print(num)
条件筛选遍历
根据条件筛选序列元素。
def filter_and_transform(numbers):
return [num * 2 for num in numbers if num > 0]
def group_by_condition(items):
result = {"valid": [], "invalid": []}
for item in items:
if isinstance(item, (int, float)):
result["valid"].append(item)
else:
result["invalid"].append(item)
return result
矩阵操作
处理二维数组。
def transpose_matrix(matrix):
return [[row[i] for row in matrix]
for i in range(len(matrix[0]))]
def matrix_operation(matrix):
rows = len(matrix)
cols = len(matrix[0])
result = [[0 for _ in range(cols)]
for _ in range(rows)]
for i in range(rows):
for j in range(cols):
result[i][j] = matrix[i][j] * 2
return result
生成器表达式
使用生成器处理大型序列。
def process_large_dataset(data):
processed = (item * 2 for item in data)
return sum(processed)
def chunk_processor(items, size):
return (items[i:i + size]
for i in range(0, len(items), size))