Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
修改条件python参数中的变量_Python_Python 3.x - Fatal编程技术网

修改条件python参数中的变量

修改条件python参数中的变量,python,python-3.x,Python,Python 3.x,我有一个while循环,它对另一个类提供的输出进行操作,直到没有输出为止 while a.is_next(): fn(a.get_next()) 是否有一种方法可以检查新项目是否存在以及是否存在。同时加载它 while b=a.get_next(): fn(b) 不确定为什么要这样做,但可以指定并检查同一语句中是否存在,如: import itertools as it for b in (x.get_next() for x in it.repeat(a) if x.is_nex

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

while a.is_next():
   fn(a.get_next())
是否有一种方法可以检查新项目是否存在以及是否存在。同时加载它

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

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

import itertools as it
for b in (x.get_next() for x in it.repeat(a) if x.is_next()):
    fn(b)
是否有一种方法可以检查新项目是否存在以及是否存在。同时加载它

while b=a.get_next():
  fn(b)
简短的回答是否定的。Python赋值不能代替while循环的条件语句。但是,为什么不在每次迭代的一个变量旁边重新分配a.get_的值,并将其用作循环条件:

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.

看起来你在试图重新创造这个世界。迭代器必须有两个方法:一个是返回迭代器本身的_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

搜索生成器、迭代器和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

嗯,出于某种奇怪的原因,我没有想到使用for循环。好主意+1.我唯一的反对意见是,这是一个有点痛的眼睛。这个功能是有争议的。。。为什么不使用迭代器协议呢?