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

查看:78
本文介绍了列表中的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.

推荐答案

您要询问的代码行正在使用

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))

说明 :

Explanation:

为了最好地解释 的工作原理,一些简单的示例可能对帮助您了解所拥有的代码很有启发性.如果您要继续使用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天全站免登陆