zoukankan      html  css  js  c++  java
  • Python generator 类型

    场景:

    使用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)]
  • 相关阅读:
    一周进度条博客
    4.8地铁查询开发进度
    4.7地铁查询开发进度
    4.6地铁查询系统开发进度
    大二下第六周学习进度报告
    4.5地铁查询系统开发进度2
    《构建之法》阅读笔记03
    石家庄地铁查询系统开发进度
    《构建之法》阅读笔记02
    大二下第五周学习笔记
  • 原文地址:https://www.cnblogs.com/peanutk/p/10643797.html
Copyright © 2011-2022 走看看