python—在“for”循环中,在循环之前访问迭代器

c2e8gylq  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(370)

我正在尝试访问“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'), MyClass('rand1', 'rand2')]

for obj in list_of_objects:
    if condition:
        # do some stuff
        pass

问题是它在定义之前就被访问了(它在for循环中被定义)。我不想在for循环中引入条件行,因为这些行在每次迭代中都会执行,没有必要这样做。
其思想是,所有这些都进入一个函数,“var1”和“age”是函数的参数。

gt0wga4j

gt0wga4j1#

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
mkh04yzy

mkh04yzy2#

你宣布 condition 作为一个简单的布尔变量,而它的值必须依赖于 obj . 可以使用一组函数并将条件赋给相关的函数,或者由于条件很简单,可以使用lambdas:
条件=obj.type==myclass.class\u 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

相关问题