【问题标题】:How make an area iterable by each point in python如何通过python中的每个点使区域可迭代
【发布时间】:2017-04-03 15:41:27
【问题描述】:

您好,我正在尝试创建一个表示可以使用 for ... in 循环迭代的区域的类。我知道这可以通过两个 for 循环来完成,但我试图从总体上理解生成器。

我正在使用 Python 3

我已经写了这个但不起作用:

class Area:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def __iter__(self):
        # my best try, clearly I don't understand 
        # something about generators
        for x in range(0, self.width):
            for y in range(0, self.height):
                yield x, y 

area = Area(2, 3)
for x, y in area:
    print("x: {}, y: {}".format(x, y))

# I want this to output something like:
#  x: 0, y: 0 
#  x: 1, y: 0
#  x: 0, y: 1
#  x: 1, y: 1
#  x: 0, y: 2
#  x: 1, y: 2

谢谢你

【问题讨论】:

  • 我尝试了您的代码,它几乎可以正常工作。究竟什么“不起作用”?
  • 尝试只用两个 for 循环迭代点,不涉及 Area 类。这可能会让你做错了什么更明显。
  • 切换 for 循环。
  • 谢谢大家,我想我的代码中还有另一个错误。我对我的问题进行了简化,这段代码有效。对不起,是我的错。

标签: python python-3.x iterator generator


【解决方案1】:

下面是一个简单的例子:

class Fib:
    def __init__(self, max):
        self.max = max

    def __iter__(self):
        // The variables you need for the iteration, to store your
        // values
        self.a = 0
        self.b = 1
        return self

    def __next__(self):
        fib = self.a
        if fib > self.max:
            raise StopIteration  // This is no error. It means, that
                                 // The iteration stops here.
        self.a, self.b = self.b, self.a + self.b
        return fib

我希望这会有所帮助。我不明白你想对你的班级做什么。 有很好的教程here

迈克尔

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-23
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多