在 Python 列表理解中可迭代

iterable in Python list comprehension

如果我有:

usernames = [user.get('username') for user in json.loads(users)]

json.loads 会像正常的 for 循环一样被调用一次还是在每次迭代中被调用多次?

别担心:它只被调用一次,尽管 language reference 在这一点上并不十分清楚:

The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new container are those that would be produced by considering each of the for or if clauses a block, nesting from left to right, and evaluating the expression to produce an element each time the innermost block is reached.

它将像正常情况一样只调用一次 for-loop。例如:

x = [2,4,6,8,10]
y = [i/2 for i in x]

输出:

>>> y
[1.0, 2.0, 3.0, 4.0, 5.0]

这里x的每个元素被调用一次为i,除以2为i/2。同样,json.loads(users)也会被调用一次。