问题描述:

I have a list of record instances returned by SQLAlchemy.

While the instances have many attributes, I want a new list with only one of the attributes. The java coder in me says:

my_records = query.all()

names = []

for my_record in my_records:

names.append(my_record.name)

...which works, of course. But What's the Pythonic answer? I know there a one-liner that includes these 4 lines into 1, but finding it is like googling for "for".

网友答案:

You are looking for what is called a list comprehension:

names = [my_record.name for my_record in query.all()]

The above is a concise equivalent to the for-loop in your example.


In addition, you should be aware that there are dict comprehensions:

{key:val for key, val in iterable}

as well as set comprehensions:

{item for item in iterable}

which will construct new dictionaries and sets respectively.


Lastly, all of these constructs allow you to add an optional condition to be tested for each item:

[item for item in iterable if condition]
{key:val for key, val in iterable if condition}
{item for item in iterable if condition}

This is useful if you want to filter the items from the iterable by the condition.

网友答案:

You want to do a list comprehension:

result = [my_record['name'] for my_record in query.all()]
网友答案:

Alternatively to list comprehension you can use operator.attrgetter and map:

map(operator.attrgetter('name'), query.all())

(But the list comprehension variant is easier to read IMO.)

相关阅读:
Top