简体   繁体   English

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

[英]Extract a list of specific attributes from a list of objects

I have a list of objects.我有一个对象列表。 Object has >10 attributes. Object 具有 >10 个属性。 I want to make a list containing only subsets of specific attributes from class.我想制作一个仅包含 class 特定属性子集的列表。

Is there any built-in functions to do that?是否有任何内置函数可以做到这一点? Or if not, what would be the most pythonic way to do this?或者如果不是,那么最pythonic的方法是什么?

I tried this, but I would prefer to have a dynamic way to reference the specific attributes (eg pass a dictionary or a similar solution, that would enable me to figure out which attributes in runtime)我试过这个,但我希望有一种动态的方式来引用特定的属性(例如,传递字典或类似的解决方案,这将使我能够找出运行时的哪些属性)

filtered_list = [[object.attr1, object.attr2] for object in list_objects]

(The solution can be just for Python 3) (解决方案可以只针对 Python 3)

Something like就像是

[[getattr(o, a) for a in ['attr1', 'attr2']] for o in objects]

should do it.应该这样做。

If you want a list of dictionaries of object attributes:如果您想要 object 属性的字典列表:

# the list of attributes to get from each object
attrs = ['attr1', 'attr2']

# using dictionary comprehension to generate the list of attributes and their values
attr_vals_dict = [{a:getattr(o, a) for a in attrs} for o in objects]

Output: Output:

[{'attr1': 1, 'attr2': 2}, {'attr1': 3, 'attr2': 4}, {'attr1': 'banana', 'attr2': 'apple'}]

As far as getting the dynamic list of attributes in the first place, that's already been answered here .至于首先获取属性的动态列表, 这里已经回答了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM