Python for-in loop preceded by a variable

前端 未结 5 889
星月不相逢
星月不相逢 2020-11-22 08:28
foo = [x for x in bar if x.occupants > 1]

After googling and searching on here, couldn\'t figure out what this does. Maybe I wasn\'t searching

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 09:28

    It's a list comprehension

    foo will be a filtered list of bar containing the objects with the attribute occupants > 1

    bar can be a list, set, dict or any other iterable

    Here is an example to clarify

    >>> class Bar(object):
    ...   def __init__(self, occupants):
    ...     self.occupants = occupants
    ... 
    >>> bar=[Bar(0), Bar(1), Bar(2), Bar(3)]
    >>> foo = [x for x in bar if x.occupants > 1]
    >>> foo
    [<__main__.Bar object at 0xb748516c>, <__main__.Bar object at 0xb748518c>]
    

    So foo has 2 Bar objects, but how do we check which ones they are? Lets add a __repr__ method to Bar so it is more informative

    >>> Bar.__repr__=lambda self:"Bar(occupants={0})".format(self.occupants)
    >>> foo
    [Bar(occupants=2), Bar(occupants=3)]
    

提交回复
热议问题