Using 'in' to match an attribute of Python objects in an array

后端 未结 8 1479
傲寒
傲寒 2021-01-07 16:25

I don\'t remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,

foo in iter_attr(array of python ob         


        
8条回答
  •  一向
    一向 (楼主)
    2021-01-07 16:35

    What I was thinking of can be achieved using list comprehensions, but I thought that there was a function that did this in a slightly neater way.

    i.e. 'bar' is a list of objects, all of which have the attribute 'id'

    The mythical functional way:

    foo = 12
    foo in iter_attr(bar, 'id')

    The list comprehension way:

    foo = 12
    foo in [obj.id for obj in bar]

    In retrospect the list comprehension way is pretty neat anyway.

提交回复
热议问题