开发者

Accessing Class Variables from a List in a nice way in Python

开发者 https://www.devze.com 2022-12-22 17:46 出处:网络
Suppose I have a list X = [a, b, c]where a, b, c are instances of the same class C. Now,all these instances a,b,c,have a variable called v,a.v,b.v, c.v ...

Suppose I have a list X = [a, b, c] where a, b, c are instances of the same class C. Now, all these instances a,b,c, have a variable called v, a.v, b.v, c.v ... I simply want a list Y = [a.v, b.v, c.v]

Is there a nice command to开发者_高级运维 do this? The best way I can think of is:

Y = []
for i in X
    Y.append(i.v)

But it doesn't seem very elegant ~ since this needs to be repeated for any given "v" Any suggestions? I couldn't figure out a way to use "map" to do this.


That should work:

Y = [x.v for x in X]


The list comprehension is the way to go.

But you also said you don't know how to use map to do it. Now, I would not recommend to use map for this at all, but it can be done:

map( lambda x: x.v, X)

that is, you create an anonymous function (a lambda) to return that attribute.

If you prefer to use the python library methods (know thy tools...) then something like:

map(operator.attrgetter("v"),X)

should also work.


I would do a list comprehension:

Y = [ i.v for i in X ]

It is shorter and more conveniant.

0

精彩评论

暂无评论...
验证码 换一张
取 消