列表中的 for 循环在 Python 中有什么作用? [英] What does a for loop within a list do in Python?

查看:22
本文介绍了列表中的 for 循环在 Python 中有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给我解释一下这个 Python 代码片段的最后一行?

Can someone explain the last line of this Python code snippet to me?

Cell 只是另一个类.我不明白如何使用 for 循环将 Cell 对象存储到 Column 对象中.

Cell is just another class. I don't understand how the for loop is being used to store Cell objects into the Column object.

class Column(object):

    def __init__(self, region, srcPos, pos):

        self.region = region
        self.cells = [Cell(self, i) for i in xrange(region.cellsPerCol)] #Please explain this line.

推荐答案

您所询问的代码行是使用 list comprehension 以创建一个列表,并将此列表中收集的数据分配给 self.cells.相当于

The line of code you are asking about is using list comprehension to create a list and assign the data collected in this list to self.cells. It is equivalent to

self.cells = []
for i in xrange(region.cellsPerCol):
    self.cells.append(Cell(self, i))

说明:

为了最好地解释如何这是如何工作的,一些简单的示例可能对帮助您理解您拥有的代码有所启发.如果您打算继续使用 Python 代码,您将再次遇到列表推导式,您可能想自己使用它.

To best explain how this works, a few simple examples might be instructive in helping you understand the code you have. If you are going to continue working with Python code, you will come across list comprehension again, and you may want to use it yourself.

请注意,在下面的示例中,两个代码段是等价的,因为它们创建了存储在列表 myList 中的值的 list.

Note, in the example below, both code segments are equivalent in that they create a list of values stored in list myList.

例如:

myList = []
for i in range(10):
    myList.append(i)

相当于

myList = [i for i in range(10)]

列表推导式也可能更复杂,例如,如果您有一些条件来确定值是否应进入列表,您也可以使用列表推导式来表达这一点.

List comprehensions can be more complex too, so for instance if you had some condition that determined if values should go into a list you could also express this with list comprehension.

这个例子只收集列表中的偶数值:

This example only collects even numbered values in the list:

myList = []
for i in range(10):
    if i%2 == 0:     # could be written as "if not i%2" more tersely
       myList.append(i)

和等效的列表推导式:

myList = [i for i in range(10) if i%2 == 0]

最后两点:

  • 你可以有嵌套"的列表理解,但它们很快就会变得难以理解:)
  • 列表解析比等效的 for 循环运行得更快,因此通常是关心效率的普通 Python 程序员的最爱.

好的,最后一个示例显示您还可以将函数应用于您在列表中迭代的项目.这使用 float() 将字符串列表转换为浮点值:>

Ok, one last example showing that you can also apply functions to the items you are iterating over in the list. This uses float() to convert a list of strings to float values:

data = ['3', '7.4', '8.2']
new_data = [float(n) for n in data]

给出:

new_data
[3.0, 7.4, 8.2]

这篇关于列表中的 for 循环在 Python 中有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆