I've got an list of o开发者_运维知识库bjects 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]
[obj.id for obj in myObjects]
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 range
.
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.
If you want a direct equivalent of C# select in Python, at the cost of using a third-party library, you could use the asq package which provides a LINQ-for-objects inspired implementation over Python iterables. Using asq the C# code in your question would become:
from asq.initiators import query
query(myObjects).select(lambda obj: obj.id)
or, combined with another feature of asq:
from asq.selectors import a_
query(myObjects).select(a_("id"))
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)
精彩评论