gpt4 book ai didi

python - 如何打印生成器对象的产生值?

转载 作者:行者123 更新时间:2023-12-01 03:49:37 26 4
gpt4 key购买 nike

我正在尝试将我创建的类制作成无限级数生成器。

类基本上是这样的(因为它很大,所以我省略了其他方法):

class Step(object):
''' A Step taken through a field. '''
def __init__(self, step_id, offset, danger,
danger_limit=None, is_encounter = None, input=None):
self.step_id = step_id
self.offset = offset
self.danger = danger
self.is_encounter = is_encounter
self.rnd = self.get_rnd(self.step_id, self.offset)
self.danger_limit = self.get_danger_limit(self.rnd)

def __repr__(self):
return '{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}'.format(
self.step_id, self.offset, self.danger,
self.rnd, self.danger_limit, self.is_encounter, self.input)

def __iter__(self):
return self

def advance_step(self, danger_inc=113):
''' To help with generator functions. '''
# Advances the current step, so make a current step object.
old_Step = Step(step_id=self.step_id, offset=self.offset, danger=self.danger)

step_id = Step.get_step_id(old_Step.step_id)
offset = Step.get_offset(step_id, old_Step.offset)
danger = Step.get_danger(danger_inc, old_Step.danger, old_Step.danger_limit)
new_step = Step(step_id = step_id, offset = offset, danger = danger)
new_step.is_encounter = Step.is_encounter(new_step.danger,
new_step.danger_limit)
return new_step

def next(self):
''' Yields next step in sequence. '''
while True:
yield self.advance_step()

我想打印一系列步骤对象。所以我尝试了这个:

def main():
step = Step(step_id=250, offset=13, danger=0)
print step.next()
# Generate next 4 steps in sequence.
for i in xrange(4):
print step.next()

但是,我得到以下输出:

<generator object next at 0x104364cd0>
<generator object next at 0x104364cd0>
<generator object next at 0x104364cd0>
<generator object next at 0x104364cd0>
<generator object next at 0x104364cd0>

预期输出应类似于一系列 Step 对象:

0   250 13  2048    0   74  19200   False   None
1 252 13 2048 2048 216 55552 False None
2 254 13 2048 4096 163 41984 False None
3 0 26 2048 6144 151 38912 False None
4 2 26 2048 8192 212 54528 False None

如果执行以下操作,我会得到预期的输出:

step2 = step.advance_step()
step3 = step2.advance_step()
step4 = step3.advance_step()
print step,'\n', step2,'\n', step3,'\n', step4

如何打印生成的步骤对象而不取回生成器对象?

我想我做错了什么,但我看不出它是什么。

最佳答案

next() 方法必须在可迭代表示的序列中返回一个值。您为每个步骤返回了一个生成器。

简单地返回下一个值,这里不需要使用循环:

def next(self):
''' Yields next step in sequence. '''
return self.advance_step()

当然,您可以将 advance_step() 重命名为 next()

来自iterator.next() documentation :

Return the next item from the container. If there are no further items, raise the StopIteration exception.

关于python - 如何打印生成器对象的产生值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38466232/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com