List comprehension
Sometimes loops are used to go through one collection of items simply to generate another
collection of (different) items. For example, here the function range(1,8) gives a sequence
[1,2,3,4,5,6,7], which is used to make a list of square numbers:
squares = []
for x in range(1,8):
squares.append(x*x)
# squares becomes [1, 4, 9, 16, 25, 36, 49]
However, when mapping one collection to another in this way, there is a neater
alternative syntax called list comprehension. And often this will allow you to map one list
of items onto another in a single line of code. In essence a list comprehension is a way of
using a loop to build a list from the inside. Here is a simple example:
squares = [x*x for x in range(1,8)] # [1, 4, 9, 16, 25, 36, 49]
The first expression inside the square brackets (x*x) is what is placed in the resulting
list, and the remainder, from the for to the closing bracket, is what generates the values for
the loop variable x. Not only is this shorter to write than a conventional for loop, it is also
computationally quicker.
Do'stlaringiz bilan baham: |