Python for-in loop preceded by a variable

前端 未结 5 887
星月不相逢
星月不相逢 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:11

    Since the programming part of question is fully answered by others it is nice to know its relation to mathematics (set theory). Actually it is the Python implementation of Set builder notation:

    Defining a set by axiom of specification:

    B = { x є A : S(x) }

    English translation: B is a set where its members are chosen from A, so B is a subset of A (B ⊂ A), where characteristic(s) specified by function S holds: S(x) == True

    Defining B using list comprehension:

    B = [x for x in A if S(x)]

    So to build B with list comprehension, member(s) of B (denoted by x) are chosen from set A where S(x) == True (inclusion condition).

    Note: Function S which returns a boolean is called predicate.

提交回复
热议问题