python中可以在for循环之前使用什么样的语句

时间:2015-05-23 19:23:31

标签: python

我在python中看到了这样的代码

    let printController = UIPrintInteractionController.sharedPrintController()!
    //The UIPrintInteractionController presents the user interface and manages the printing.

    let printinfo = UIPrintInfo(dictionary: nil)!

    //The UIPrintinfo object contains information about the print job. This information is assigned to the printInfo property of the UIPrintInteractionController.


    printinfo.outputType = UIPrintInfoOutputType.General
    printinfo.jobName = "Print Job"
    printController.printInfo = printinfo
    //The printing text can be formatted, here we define the insets for the printing page.

    let formatter = UIMarkupTextPrintFormatter(markupText: lblOutput.text)
    formatter.contentInsets = UIEdgeInsets(top: 72, left: 72, bottom: 72, right: 72)
    printController.printFormatter = formatter
    printController.presentAnimated(true, completionHandler: nil)
    //The user is presented the iPhone printing interface to select a printer and the number of copies.

这会产生一个2d数组的数组。 x的值为

x = [[0] * 2 for i in range(2)]

我的问题是我们可以在for循环前放置什么样的语句?我不太明白如何使用它。在python中是否有这种用途的名称?这是一个好习惯(pythonic)吗?

2 个答案:

答案 0 :(得分:2)

任何表达式都可以放在列表理解中的for之前,尽管它几乎总是与for和{{之间的名称相关的表达式1}}。

相关的是生成器表达式(又名genexs),它们不包括方括号。它们依次产生每个结果项而不是一次生成整个列表。

答案 1 :(得分:0)

该代码使用带有列表的mutiplication运算符,例如[0] * 3生成结果[0, 0, 0]

要创建3x3矩阵,可能会尝试使用

M = [[0] * 3] * 3

但这不会按预期工作。原因是结果在打印时看起来显然是正确的,但它会表现得很奇怪,因为*运算符只是在外部列表中放置相同行的三倍。

换句话说,更改后例如M[0][1]M[1][1]也会显示为已修改,因为M[0]M[1]确实是相同的列表对象。

因此,解决方案是使用

M = [[0] * num_cols for i in range(num_rows)]

因为[<expr> for <var> in <iterable>]为每次迭代生成一个评估<expr>的列表,因此每次都会生成一个不同的列表对象。

您可以在<expr>中使用任何Python表达式,在大多数情况下,它将是一个取决于<var>的表达式,但这不是必需的。