场景: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)]