从列表中提取所需元素并创建另一个列表

时间:2017-05-18 22:28:21

标签: python python-2.7

我有以下列表,其中我只想提取名称并制作另一个列表。有人可以帮助我实现这个目标吗?

>>> a = [{'name': 'mytestbuild', 'notes': 'Autocreated build.', 'testplan_id': '178775', 'closed_on_date': '', 'release_date': '', 'is_open': '1', 'active': '1', 'creation_ts': '2017-05-09 11:20:25', 'id': '160'}, {'name': 'mytestbuild_delete', 'notes': 'Autocreated build.', 'testplan_id': '178775', 'closed_on_date': '', 'release_date': '', 'is_open': '1', 'active': '1', 'creation_ts': '2017-05-18 15:24:37', 'id': '164'}]

由此,我想获得仅“名称”的列表,即

name_list = ['mytestbuild', 'mytestbuild_delete']

这不起作用:

>>> a['name']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str

1 个答案:

答案 0 :(得分:0)

你应该这样做

print (a[0]['name'])

这将打印

mytestbuild

并将其列入列表

lis= [m['name'] for m in a]
print (lis)

这将打印列表

['mytestbuild', 'mytestbuild_delete']