Python generator 类型

我只是一个虾纸丫 提交于 2020-12-16 20:15:10

场景:

使用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 a list argument (the most common type of Iterable) 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 more if clauses. The following example builds a list of tuples containing all x,y pairs where x and y are both less than 4 and x is less than y:

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)]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!