场景:
使用gurobi求解优化问题时,遇到quicksum()函数用法如下:
quicksum(mu[i] for i in range(n))
读着很流畅而且好像并没什么问题欸,但
mu[i] for i in range(n)
返回的又是什么?
看了下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?
python console中试了下:
x = [1,2,3]
print (x[i] for i in range(2))
<generator object <genexpr> at 0x000000000449A750>
并不是list欸,是个generator object。
难道说generator object可以赋值给list变量?
查了下generator的相关文章(其中的yeild是关键 ,参考yeild介绍)
然后是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)]
来源:oschina
链接:https://my.oschina.net/u/4360005/blog/3588555