1

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.

3 Answers 3

11

That should work:

Y = [x.v for x in X]
Sign up to request clarification or add additional context in comments.

Comments

5

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.

2 Comments

@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.
2 things I thought after reading the question were, definitely map .. ah wait how about itemgetter. +1 for you.
2

I would do a list comprehension:

Y = [ i.v for i in X ]

It is shorter and more conveniant.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.