How to extract from a list of objects a list of specific attribute?

前端 未结 4 940
走了就别回头了
走了就别回头了 2020-11-30 06:24

I have a list of objects. Object has 3 string attributes. I want to make a list containing only a specific attribute from class.

Is there any built-in functions to d

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 06:59

    A list comprehension would work just fine:

    [o.my_attr for o in my_list]
    

    But there is a combination of built-in functions, since you ask :-)

    from operator import attrgetter
    map(attrgetter('my_attr'), my_list)
    

提交回复
热议问题