c# - net - visual basic
Python equivalent of C#'s.Select? (4)
I've got an list of objects in Python, and they each have an
id property. I want to get a list of those IDs.
In C# I'd write
myObjects.Select(obj => obj.id);
How would I do this in Python?
Check out the section on "List Comprehension" here: http://docs.python.org/tutorial/datastructures.html
If your starting list is called
original_list and your new list is called
id_list, you could do something like this:
id_list = [x.id for x in original_list]
If it's a big list and you only need to process the ids once then there are also generator expressions.
ids = (obj.id for obj in my_objects) for id in ids: do_something(id)
A generator expression doesn't support random access but will get you each id on demand and so avoids building a list all at once. generator expressions are to
xrange as list comprehensions are to
One more caveat with generator expressions is that it can only be accessed for as long as any resource within it is still open. For example, the following code will fail.
with open(filename) as f: lines = (line for line in f) # f is now closed for line in lines: print line
The equivalent list comprehension would work in this case.
Nobody in their right mind would do this the following way, but here it is in case it comes in handy in a more complex example
import operator map(operator.attrgetter("id"), myObjects)
[obj.id for obj in myObjects]