python - 在列表中转换产量
问题描述
我有这个代码:
def sumto(n, lst):
if not n and not lst: # base case 1: empty list = 0
yield []
return
if n < 0 or not lst: # base case 2: unsolvable
return
head, *tail = lst
for sol in sumto(n-head, tail): # recursion 1: use first element
yield [head] + sol
yield from sumto(n, tail) # recursion 2: don't use first element
我想将产量转换成一个列表。我该怎么做?所以我只想不使用 yield 但是例如 my_list.append
解决方案
这是等价的:
def sumto(n, lst):
result = []
if not n and not lst:
result.append([])
return result
if n < 0 or not lst:
return result
head, *tail = lst
for sol in sumto(n-head, tail):
result.append([head] + sol)
result.extend(sumto(n, tail))
return result
以下规则可以相当普遍地应用于将生成器函数转换为返回 a 的函数list
:
return
# =>
return result
# also think of an implicit "return" at the end of the generator function
yield x
# =>
result.append(x)
yield from x
# =>
result.extend(x)
但是,通常,您应该努力以相反的方式转换您的代码。生成器是 Python 最好的之一。它们允许您迭代所有元素,而无需将所有元素都保存在内存中,它们只进行生成工作,直到您找到所需的内容。如果你想要一份清单,就打电话list(...)
给他们。
推荐阅读
- mysql - 使用 Terraform 创建 AWS MySQL RDS 实例时出错
- angular - 滚动角载荷数据 [For 循环]
- jquery - JQuery .Sortable 恢复移动 LI
- css - Flexbox 订购和包装 3 件商品
- ios - iOS(Swift):Collection View indexPath(for:cell)对于不可见单元格为零
- sql - 在“From”和“To”字段中的值之间查找值并更新表
- javascript - 在画布中定位模态对话框
- javascript - 计算日期的问题
- python - wxPython dataviewcustomrenderer 左键单击事件不会触发
- sass - 添加图标字体 ionic 3 时出错