开发者

Is there a better way to do this in Python?

开发者 https://www.devze.com 2023-01-20 06:04 出处:网络
ids = [] for object in o开发者_如何学Cbjects: ids += [object.id] You can use a list comprehension:
ids = []

for object in o开发者_如何学Cbjects:
  ids += [object.id]


You can use a list comprehension:

ids = [object.id for object in objects]

For your reference:

  • http://docs.python.org/howto/functional.html#generator-expressions-and-list-comprehensions

Both produce the same result. In many cases, a list comprehension is an elegant and pythonic way to do the same as what you mentioned.


The standard (i.e “pythonic” a.k.a cleanest :) way is to use a list comprehension:

ids= [obj.id for obj in objects]

The above works for all Python versions ≥ 2.0.

Other ways (just FYI)

In Python 2, you can also do:

ids= map(lambda x: x.id, objects)

which should be the slowest method, or

# note: Python ≥ 2.4
import operator
ids= map(operator.attrgetter('id'), objects)

which might be the fastest method, although I assume the difference won't be that much; either way, the clarity of the list comprehension outweighs speed gains.

Should you want to use an alternative way in Python 3, you should enclose the map call in a list call:

ids= list(map(operator.attrgetter('id'), objects))

because the map builtin returns a generator instead of a list in Python 3.


Another way:

ids = map(lambda x: x.id, objects)


You don't need the operator module:

In [12]: class Bar(object):
             def __init__(self, id_):
                 self.id = id_         

In [15]: foo = [Bar(1) for _ in xrange(10000)]

In [16]: foobar = map(lambda bar: getattr(bar, 'id'), foo)

In [17]: len(foobar)
Out[17]: 10000

In [18]: foobar[:10]
Out[18]: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
0

精彩评论

暂无评论...
验证码 换一张
取 消