从对象列表中获取特定属性

时间:2015-10-07 10:44:25

标签: python python-2.7

我有一个如下所示的列表

[
<NodeImage: id=aki-00501552,
name=ubuntu/kernels-testing/ubuntu-lucid-amd64-linux-image-2.6.32-341-ec2-v-2.6.32-341.42-kernel,
driver=AmazonEC2(ap-southeast-1)...>,
<NodeImage: id=aki-00c4bd52,
name=ubuntu-kernels/ubuntu-lucid-amd64-linux-image-2.6.32-316-ec2-v-2.6.32-316.31-kernel,
driver=AmazonEC2(ap-southeast-1)...>,
<NodeImage: id=aki-015d1253,
name=RH-pv-grub-hd00-V1.01-x86_64,
driver=AmazonEC2(ap-southeast-1)...>
]

该列表包含多个&#34; NodeImage&#34;并且每个人都有id,name和driver属性。如何获取所有ID并存储在不同的列表中?

1 个答案:

答案 0 :(得分:1)

你有一个对象列表;要创建特定属性值的列表,请使用list comprehension

ids = [node.id for node in list_of_nodes]

如果并非所有对象都具有该属性,则可以包含过滤器:

ids = [node.id for node in list_of_nodes if hasattr(node, 'id')]