修改条件 Python 参数中的变量



我有一个 while 循环,它对另一个类提供的输出进行操作,直到没有输出。

while a.is_next():
fn(a.get_next())

有没有办法检查新项目是否存在并同时"加载"它?

while b=a.get_next():
fn(b)

看起来你正在尝试重新发明迭代器。 迭代器必须有两个方法:返回迭代器本身的__iter__方法和返回下一项或引发StopIteration__next__方法。 例如

class MyIterator:
def __init__(self):
self.list = [1, 2, 3]
self.index = 0
def __iter__(self):
return self
def __next__(self):
try:
ret = self.list[self.index]
self.index += 1
return ret
except IndexError:
raise StopIteration

对于这个例子来说,这很多,但它允许我们在Python期望迭代器的任何地方使用该迭代器。

for x in MyIterator():
print(x)
1
2
3

不确定为什么要这样做,但您可以分配并检查是否存在在同一语句中,例如:

import itertools as it
for b in (x.get_next() for x in it.repeat(a) if x.is_next()):
fn(b)

有没有办法检查新项目是否存在并同时"加载"它?

简短的回答是否定的。Python 赋值不能代替while循环的条件语句来完成。但是,为什么不简单地在每次迭代中将a.get_next()的值重新分配给变量,并将其用作循环条件:

b = a.get_next() # get the initial value of b
while b:
fn(b)
b = a.get_next() # get the next value for b. If b is 'fasly', the loop will end.

搜索生成器、迭代器和 yield 语句。

代码示例

class Container:
def __init__(self,l):
self.l = l
def next(self):
i = 0
while (i < len(self.l)):
yield self.l[i]
i += 1
c = Container([1,2,3,4,5])

for item in c.next():
print(item, end=" ") # 1 2 3 4 5

最新更新