views:

80

answers:

3

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.

+10  A: 

That should work:

Y = [x.v for x in X]
FlorianH
This is a great shorthand, thanks!
Deniz
+1 more list comprehension please
jeffjose
+2  A: 

I would do a list comprehension:

Y = [ i.v for i in X ]

It is shorter and more conveniant.

Juergen
+5  A: 

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.

extraneon
This is very helpful, thank you.
Deniz
@Deniz I think it's fair to award the answer to FlorianH as he really has the best solution in this case, and was first with the answer. My answer was more intended to show alternative ways, and to show how to use map in this case.
extraneon
Good point ~ done! :)
Deniz
2 things I thought after reading the question were, definitely `map` .. ah wait how about `itemgetter`. +1 for you.
jeffjose