简体   繁体   English

迭代(yield)一个列表

[英]Iterating (yield) over a list

I'm trying to make a method that iterates over a list and returns the next element.我正在尝试创建一个遍历列表并返回下一个元素的方法。

That's my list:那是我的清单:

[2, 5, 7, 10, 25, 30, 50, 70] [2, 5, 7, 10, 25, 30, 50, 70]

That's the method I'm working on:这就是我正在研究的方法:

    def iterDenominations(self):
        it = iter(self.listDenominations)
        yield it.__next__()

When I call the method and print the result当我调用该方法并打印结果时

firstCall = C.iterDenominations()
print(firstCall)
secondCall = C.iterDenominations()
print(secondCall)

, the first two prints are: ,前两个打印是:

<generator object Currency.iterDenominations at 0x000001D413F6DC10> <生成器 object Currency.iterDenominations 位于 0x000001D413F6DC10>

<generator object Currency.iterDenominations at 0x000001D4140E2EB0> <生成器 object Currency.iterDenominations 位于 0x000001D4140E2EB0>

What should I do to print '2', '5', '7', ...?我应该怎么做才能打印“2”、“5”、“7”……? Thanks you谢谢

yield always creates a new generator. yield总是创建一个新的生成器。 iterDenominations doesn't return the next/first element of self.listDenominations ; iterDenominations不返回的下一个/第一元件self.listDenominations ; it returns a generate that will yield that single element.它返回一个生成该单个元素的生成。

If you want to create your own iterator, you can do it the long with with如果你想创建自己的迭代器,你可以用

def iterDenominations(self):
    it = iter(self.listDenominations)
    for x in it:
        yield x

the shorter way更短的路

def iterDenominations(self):
    for x in self.listDenominations:
        yield x

or an even shorter way:或者更短的方式:

def iterDenominations(self):
    yield from self.listDenominations

or the shortest way或者最短的路

def iterDenominations(self):
    return iter(self.listDenominations)

(OK, that's actually two characters longer. But it might look more familiar.) (好吧,这实际上长了两个字符。但它可能看起来更熟悉。)

For that to work, you need to store the state somewhere and then a custom function is a difficult start.为此,您需要将 state 存储在某个地方,然后自定义 function 是一个困难的开始。 I believe you want to use the iterator as it is:我相信您想按原样使用迭代器:

it = iter(my_list)
print(next(it))
print(next(it))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM