場景:html
使用gurobi求解優化問題時,遇到quicksum()函數用法以下:python
quicksum(mu[i] for i in range(n))
讀着很流暢並且好像並沒什麼問題欸,但express
mu[i] for i in range(n)
返回的又是什麼?less
看了下quicksum()函數的介紹:函數
def quicksum(p_list): # real signature unknown; restored from __doc__ """ ROUTINE: quicksum(list) PURPOSE: A quicker version of the Python built-in 'sum' function for building Gurobi expressions. ARGUMENTS: list: A list of terms. RETURN VALUE: An expression that represents the sum of the input arguments. EXAMPLE: expr = quicksum([x, y, z]) expr = quicksum([1.0, 2*y, 3*z*z]) """ pass
因此,上述代碼返回的是個list?post
python console中試了下:優化
x = [1,2,3] print (x[i] for i in range(2)) <generator object <genexpr> at 0x000000000449A750>
並非list欸,是個generator object。ui
難道說generator object能夠賦值給list變量?url
查了下generator的相關文章(其中的yeild是關鍵 ,參考yeild介紹)spa
而後是generator和list~迭代器的關係
Python關鍵字yield詳解以及Iterable 和Iterator區別
A generator expression can be used whenever a method accepts an
Iterable
argument (something that can be iterated over). For example, most Python methods that accept alist
argument (the most common type ofIterable
) will also accept a generator expression.
In:(x*x for x in range(3)) Out:<generator object <genexpr> at 0x00000000045E8AF8> In:[x*x for x in range(3)] Out:[0, 1, 4]
其餘的一些補充,關於與for語句的結合:
List comprehension and generator expressions can both contain more than one
for
clause, and one or moreif
clauses. The following example builds a list of tuples containing allx,y
pairs wherex
andy
are both less than 4 andx
is less thany
:gurobi> [(x,y) for x in range(4) for y in range(4) if x < y] [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]Note that the
for
statements are executed left-to-right, and values from one can be used in the next, so a more efficient way to write the above is:gurobi> [(x,y) for x in range(4) for y in range(x+1, 4)]