当遍历以下生成器表达式时,
fun(i) for i in mylist if i not in setA.union(setB)
是在每次迭代中调用
setA.union
方法,还是只调用一次? 最佳答案
使用dis
模块的简单证明:
In [24]: def func():
....: a=set([1,2,3])
....: b=set([3,4,5])
....: c=[i for i in xrange(10) if i in a.union(b)]
....:
In [25]: dis.dis(func)
4 42 BUILD_LIST 0
45 LOAD_GLOBAL 1 (xrange)
48 LOAD_CONST 6 (10)
51 CALL_FUNCTION 1
54 GET_ITER #iterator returned from xrange
>> 55 FOR_ITER 33 (to 91) #until the iterator is not exhausted
58 STORE_FAST 2 (i)
61 LOAD_FAST 2 (i)
64 LOAD_FAST 0 (a)
67 LOAD_ATTR 2 (union)
70 LOAD_FAST 1 (b)
73 CALL_FUNCTION 1 #union() is being called in each iteration
76 COMPARE_OP 6 (in)
79 POP_JUMP_IF_FALSE 55
82 LOAD_FAST 2 (i)
85 LIST_APPEND 2
88 JUMP_ABSOLUTE 55
#end of loop
>> 91 STORE_FAST 3 (c)
94 LOAD_CONST 0 (None)
97 RETURN_VALUE
因此,对于您的示例,它将在每次迭代中被调用,即
len(mylist)
倍。