python - 如何在不创建新生成器的情况下在 Python 中获取生成器的新输入
问题描述
我尝试编写获取列表并使用 yield 语句生成所有这些转换的代码。
问题是,当我想通过使用 send 函数为生成器获取新输入时,我会继续获取旧输入。
def permute(items):
permutations = [x for x in itertools.permutations(items)]
permutations.sort()
for n in permutations:
yield (n)
g = permute(['b','a','c'])
print(next(g)) #('a', 'b', 'c')
print(next(g)) #('a', 'c', 'b')
g.send(['e','q','c'])
print(next(g)) #('b', 'c', 'a') need to be ('c', 'e', 'q')
如何在不创建新生成器的情况下清空排列列表并重复排序排列列表步骤?
解决方案
为什么不创建一个新的类型对象permute
并使用它
import itertools
def permute(items):
permutations = [x for x in itertools.permutations(items)]
permutations.sort()
for n in permutations:
yield (n)
g = permute(['b','a','c'])
print(next(g)) #('a', 'b', 'c')
print(next(g)) #('a', 'c', 'b')
g = permute(['e','q','c'])
print(next(g)) #('b', 'c', 'a') need to be ('c', 'e', 'q')
#I get ('c', 'e', 'q')
推荐阅读
- mysql - 如何在 MySQL 上循环表行并获取表头 - 值对
- android - 未检测到 Firebase 远程配置条件国家/地区
- ocaml - Ocalmfind 找不到 Z3 包
- apache-kafka - kafka-consumer 在赔偿期间如何工作?
- python - 反 ROC-AUC 值?
- perl - 如何在 perl 中使用对象对哈希进行排序
- libgit2 - 如何从给定文件提交?
- dialogflow-es - DialogFlow 必需参数寿命
- c# - 如何在 TabPage 标题旁边显示 ErrorProvider 错误图标?
- postgresql - ASP NET CORE 部署无法访问我在 Postgresql 上的数据库