簡體   English   中英

如何使區域在python中的每個點都可迭代

[英]How make an area iterable by each point in python

您好,我正在嘗試制作一個表示可以用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

謝謝

這是一個簡單的示例,它如何工作:

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

我希望這有幫助。 我不明白您想在課堂上做什么。 這是一個很好的教程在這里

麥可

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM