网站首页 > 技术文章 正文
1.内置函数的高阶用法。
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16]
```
- **`filter()`**:筛选满足条件的元素。
```python
even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
```
- **`zip()`**:将多个可迭代对象合并为元组。
```python
a = [1, 2, 3]
b = ['a', 'b', 'c']
combined = list(zip(a, b)) # [(1, 'a'), (2, 'b'), (3, 'c')]
```
- **`enumerate()`**:同时获取索引和元素。
```python
for index, value in enumerate(numbers):
print(f"Index {index}: {value}")
```
---
#### 2. **迭代器与生成器**
- **生成器表达式**:节省内存的遍历方式。
```python
# 计算平方数的生成器
squares = (x**2 for x in range(5))
for num in squares:
print(num) 输出 #0,1,4,9,16
```
- **`yield`关键字**:创建自定义生成器。
```python
def my_generator(n):
for i in range(n):
yield i
gen = my_generator(3)
print(next(gen)) # 0
print(next(gen)) # 1
print(next(gen)) # 2
```
- **`__iter__()` 和 `__next__()`**:实现自定义迭代器。
```python
class MyIterator:
def __init__(self, max_value):
self.max_value = max_value
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current >= self.max_value:
raise StopIteration
value = self.current
self.current += 1
return value
it = MyIterator(3)
for num in it:
print(num) # 输出0,1,2
```
---
#### 3. **列表推导式**
- 列表推导式是一种简洁的遍历方式,支持条件判断和嵌套循环。
```python
# 嵌套循环
matrix = [[1, 2], [3, 4]]
flattened = [num for row in matrix for num in row] # [1,2,3,4]
# 条件判断
even_squares = [x**2 for x in range(5) if x % 2 == 0] # [0,4,16]
```
---
#### 4. **多线程与异步遍历**
- **`threading`模块**:在多个线程中并行处理任务。
```python
import threading
def process_item(item):
print(f"Processing {item}")
items = [1, 2, 3, 4]
threads = []
for item in items:
thread = threading.Thread(target=process_item, args=(item,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
```
- **`asyncio`库**:异步遍历和协程。
```python
import asyncio
async def process_item(item):
print(f"Processing {item}")
await asyncio.sleep(1)
async def main():
items = [1, 2, 3, 4]
tasks = [process_item(item) for item in items]
await asyncio.gather(*tasks)
asyncio.run(main())
```
---
#### 5. **其他高级技巧**
- **`itertools`模块**:提供高效的迭代工具。
```python
import itertools
# 无限迭代
counter = itertools.count(start=1)
for _ in range(3):
print(next(counter)) # 输出1,2,3
# 组合与排列
combinations = itertools.combinations([1,2,3], 2)
print(list(combinations)) # [(1,2), (1,3), (2,3)]
```
- **装饰器模式**:增强遍历功能。
```python
def log_decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
print(f"Logged: {result}")
return result
return wrapper
@log_decorator
def get_item(index):
return f"Item {index}"
for i in range(3):
get_item(i)
# 输出:
# Logged: Item 0
# Logged: Item 1
# Logged: Item 2
Python的遍历机制非常灵活,可以通过内置函数、生成器、列表推导式、多线程和异步等方式实现高效和优雅的代码。选择合适的遍历方法取决于具体需求,例如性能优化、代码简洁性或并行处理等。
- 上一篇: Python高级排序算法应用
- 下一篇: Python的logging功能:程序身边的日志管家
猜你喜欢
- 2025-05-16 Python随机模块22个函数详解
- 2025-05-16 Linux 命令 su 和 sudo 的区别?
- 2025-05-16 快速掌握Python时间函数的常用知识
- 2025-05-16 Java对比学习Python之高级特性:IO编程
- 2025-05-16 通俗地讲解Python的装饰器
- 2025-05-16 零起点Python机器学习快速入门-8-5-批量调用机器学习
- 2025-05-16 Python的logging功能:程序身边的日志管家
- 2025-05-16 Python高级排序算法应用
- 2025-05-16 Python 惰性计算:让代码 “懒” 出高效与优雅
- 2025-05-16 人工智能数学基础2:指数、方根及对数运算公式
- 05-25Python 3.14 t-string 要来了,它与 f-string 有何不同?
- 05-25Python基础元素语法总结
- 05-25Python中的变量是什么东西?
- 05-25新手常见的python报错及解决方案
- 05-2511-Python变量
- 05-2510个每个人都是需要知道Python问题
- 05-25Python编程:轻松掌握函数定义、类型及其参数传递方式
- 05-25Python基础语法
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 91℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 81℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)