这是我的代码:
a=[{'x':'aaa','b':'bbbb'},{'x':'a!!!','b':'b!!!'},{'x':'2222','b':'dddd'},{'x':'ddwqd','b':'dwqd'}]
Run Code Online (Sandbox Code Playgroud)
我希望得到每个'x'列表,如下所示:
['aaa','a!!!','2222','ddwqd']
Run Code Online (Sandbox Code Playgroud)
这是获得这个的最好方法,
用地图?
谢谢
list comprehension可以获得你的x值
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']
>>>
Run Code Online (Sandbox Code Playgroud)
您有一个包含3个词典的列表,并且您正在尝试使用键"x"获取每个词典的值.
您可以使用简单的列表理解来实现这一目标
[ 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
Run Code Online (Sandbox Code Playgroud)
列表理解的作用类似于:
x_values = []
for dictionary in a:
x_values.append(dictionary['x'])
Run Code Online (Sandbox Code Playgroud)
这是一篇关于列表推导效率的有趣博客文章
归档时间: |
|
查看次数: |
89 次 |
最近记录: |