What does a for loop within a list do in Python?

前端 未结 2 1250
太阳男子
太阳男子 2020-11-27 03:41

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

Cell is just another class. I don\'t understand how the for loop is be

2条回答
  •  半阙折子戏
    2020-11-27 04:07

    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:

    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.

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

    For instance:

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

    is equivalent to

    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)
    

    and the equivalent list comprehension:

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

    Two final notes:

    • You can have "nested" list comrehensions, but they quickly become hard to comprehend :)
    • List comprehension will run faster than the equivalent for-loop, and therefore is often a favorite with regular Python programmers who are concerned about efficiency.

    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]
    

    gives:

    new_data
    [3.0, 7.4, 8.2]
    

提交回复
热议问题