如何在列表理解中赋值

How to assign value inside list comprehension

如何从[列表理解内部]为对象的 .ID 属性赋值?

class C(object):
    def __init__(self): 
        self.ID=0

l=[C() for i in range(4)]
print l

t=[c for c in l if c.ID+1]
for c in t: print c.ID,

[<main.C object at 0x10454de50>, <main.C object at 0x10454ded0>, <main.C object at 0x10454df90>, <main.C object at 0x10455b150>]

0 0 0 0

[Finished in 0.1s]

编辑

如何使用列表理解更改 i

l=[i for i in range(4)]
i=0
t=[c for c in l if i++]
print i

您可以定义一个简单的函数来执行转换:

def foo(c):
    c.ID += 1
    return c

然后在列表理解中使用它:

>>> t=[foo(c) for c in l]
>>> for c in t: print c.ID,
1 1 1 1
>>> for c in l: print c.ID,
1 1 1 1

请注意,在 C 的构造函数中添加一个 ID 参数可能是个好主意,这样您就可以使用您想要的任何 ID 构造 C 对象:

class C(object):
    def __init__(self, ID=0): 
        self.ID=ID

然后

>>> a = [c(42) for _ in xrange(4)]
>>> b = [c(i) for i in xrange(4)]
>>> for c in a: print c.ID,
42 42 42 42
>>> for c in b: print c.ID,
>>> 0 1 2 3