【问题标题】:How to get new input to generator in Python without create a new generator如何在不创建新生成器的情况下在 Python 中获取生成器的新输入
【发布时间】:2019-09-21 18:42:14
【问题描述】:

我尝试编写获取列表并使用 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')

如何在不创建新生成器的情况下清空排列列表并重复排序排列列表步骤?

【问题讨论】:

  • 您在对需要使用send 的答案的评论中提到。你能解释一下为什么你需要在这里这样做吗?这是一个家庭作业吗,目的是教你send 的工作原理?

标签: python yield


【解决方案1】:

为什么不直接创建一个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')

【讨论】:

    猜你喜欢
    • 2012-08-05
    • 2018-12-18
    • 2022-12-14
    • 2013-04-20
    • 2017-02-25
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多