开发者

best way to get right thing using python

this is my code :

a=[{'x':'aaa','b':'bbbb'},{'x':'a!!!','b':'b!!!'},{'x':'2222','b':'dddd'},{'x':'ddwqd','b':'dwqd'}]

a开发者_开发知识库nd i want get every 'x' list like this :

['aaa','a!!!','2222','ddwqd']

so which is the best way to get this ,

use map ??

thanks


list comprehension can get your x values

Python 2.7.0+ (r27:82500, Sep 15 2010, 18:04:55) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a=[{'x':'aaa','b':'bbbb'},{'x':'a!!!','b':'b!!!'},{'x':'2222','b':'dddd'},{'x':'ddwqd','b':'dwqd'}]
>>> x_values = [ dictionary['x'] for dictionary in a ]
>>> print x_values
['aaa', 'a!!!', '2222', 'ddwqd']
>>> 

You have a list of 3 dictionaries and you are trying to get the value of each using the key 'x'.

The simple list comprehension that you can use to achieve this can be broken down

[ dictionary['x'] for dictionary in a ]

[ <object>                 for          <object>           in        <iterable> ]
      |                                     |
 -This is what goes into the new list  -Name object from iterable)
 -You are allowed to process the
  objects from the iterable before 
  they go into the new list

What the list comprehension does is similar to:

x_values = []
for dictionary in a:
    x_values.append(dictionary['x'])

here is an interesting blog post about the efficiency of list comprehensions

list comprehension efficiency


list comprehension:

[i['x'] for i in a]


List comprehensions are the more idiomatic choice for this sort of thing, but if you wanted to use map the code would be

 result = map(lambda item: item["x"], a)

or

 def get_x(item):
     return item["x"]

 result = map(get_x, a)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜