def chain(*iterables):
for it in iterables:
for element in it:
yield element
# 使用 yield from 优化上述代码
def chain_with_yield_from(*iterables):
for it in iterables:
yield from it
# 示例使用
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
combined = list(chain_with_yield_from(list1, list2))
print(combined) # 输出: [1, 2, 3, 'a', 'b', 'c']
# 解释说明:
# 1. `chain` 函数通过嵌套的 for 循环来遍历多个可迭代对象,并逐个生成元素。
# 2. `chain_with_yield_from` 函数使用 `yield from` 语句简化了代码,直接将子生成器的值委托给调用者。
# 3. `yield from` 不仅可以简化代码,还可以提高性能,因为它减少了额外的循环和函数调用开销。
上一篇:python常用命令
下一篇:python递归函数怎么写
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站