[英]iterable in Python list comprehension
If I have:如果我有:
usernames = [user.get('username') for user in json.loads(users)]
Will the json.loads be called once as in normal for loop or many times on each iteration? json.loads 会像正常的 for 循环一样被调用一次,还是在每次迭代中被调用多次?
Don't worry: it is called only once, although the language reference isn't exactly clear on this point:别担心:它只被调用一次,尽管语言参考在这一点上并不完全清楚:
The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses.
理解由一个表达式组成,后跟至少一个 for 子句和零个或多个 for 或 if 子句。 In this case, the elements of the new container are those that would be produced by considering each of the
for
orif
clauses a block, nesting from left to right, and evaluating the expression to produce an element each time the innermost block is reached.在这种情况下,新容器的元素是通过将每个
for
或if
子句视为一个块,从左到右嵌套,并在每次到达最里面的块时评估表达式以产生一个元素而产生的元素。
It will be called only once as in a normal for-loop.它只会被调用一次,就像在正常的 for 循环中一样。 For example:
例如:
x = [2,4,6,8,10]
y = [i/2 for i in x]
Output: Output:
>>> y
[1.0, 2.0, 3.0, 4.0, 5.0]
Here each element of x
is called once as i
and divided by 2 as i/2
.这里
x
的每个元素被称为i
并除以 2 作为i/2
。 Similarly, json.loads(users)
will also be called once.同样,
json.loads(users)
也会被调用一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.