如何解决在循环之前访问“for”循环中的迭代器
我试图在像这样的“for”循环之前访问迭代器“obj”
class MyClass:
CLASS_CONST1 = 'some_rand_const'
def __init__(self,type,age):
self.type = type
self.age = age
var1 = 5
age = 7
# # I tried to individually add the following lines here,none of them work
# obj = MyClass
# obj = MyClass()
condition = obj.type == MyClass.CLASS_CONST1
if var1 > 10:
condition = obj.type == MyClass.CLASS_CONST1 and obj.age == age
list_of_objects = [MyClass('rand1','rand2'),MyClass('rand1','rand2')]
for obj in list_of_objects:
if condition:
# do some stuff
pass
问题在于它在定义之前被访问(它在 for 循环中定义)。而且我不想在 'for' 循环中引入条件行,因为这些行将在每次迭代中执行,而没有必要这样做。
这个想法是所有这些都进入一个函数,'var1' 和 'age' 是函数的参数。
解决方法
obj = MyClass
只是将类对象(不是实例)分配给另一个变量。 obj = MyClass()
将引发错误,因为您尚未提供 type
中所需的 age
和 __init__
值。你试过 obj = MyClass(var1,age)
吗?你后来为 list_of_objects
做了。
无论如何,您已经尝试将 condition
创建为应该在迭代期间应用自身的变量。这不是 Python 的工作方式。当它被评估一次时,它被赋予一个静态值。要将其应用于所有对象,请将 condition
作为函数,该函数将对象或两个变量 type
和 var
作为参数,然后返回检查结果:>
var1 = 5
age = 7
def condition(obj):
# will return the True/False result of the check below
return obj.type == MyClass.CLASS_CONST1 and obj.age == age
for obj in list_of_objects:
if condition(obj): # call the function with that object
# do some stuff
pass
从您的代码中,不清楚您想要在 condition
中做什么。也许是这个?
var1 = 5 # or put these inside `condition` so they are local
age = 7 # to condition and not globals.
# Or pass them in as parameters and modify `condition` to accept
# the additional params
def condition(obj):
result = obj.type == MyClass.CLASS_CONST1
if result and var1 > 10:
# don't re-check `obj.type == MyClass.CLASS_CONST1`
result = obj.age == age
return result
,
您将 condition
声明为一个简单的布尔变量,而其值必须取决于 obj
的当前值。您可以使用一堆函数并将条件分配给相关的函数,或者由于条件很简单,您可以使用 lambda:
条件 = obj.type == MyClass.CLASS_CONST1
if var1 > 10:
condition = lambda obj: obj.type == MyClass.CLASS_CONST1 and obj.age == age
else:
condition = lambda obj: obj.type == MyClass.CLASS_CONST1
然后将其用作变量函数:
for obj in list_of_objects:
if condition(obj):
# do some stuff
pass
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。