As with the list,
List Inference TypeThe square brackets [] are also represented, and a shortened version of the For loop is used, the first part is an expression that generates the result list element, and the second part is a loop on an input expression. The recommended practice for reading Comprehension list expressions is to start with the inside for loop, look to the right for an if condition, and then map the expression that starts with the derivation to each matching element.
>>> even_numbers = [x for x in range (ten) if x%2 = 0]
>>> even_numbers
[0,2,4,6,8]
The above example shows the use of an if statement to filter elements.
Python also supports a structure similar to a list expression, called a generator expression (generator expression), which is basically consistent with the use of list derivations, except that it has a feature called "Lazy computing." It works by processing one object at a time, rather than at a single breath, to process and construct the entire data structure, and the potential advantage is that it can save a lot of memory .
>>> even_numbers = (x for x in range (10000) if x%2 = 0)
>>> even_numbers
<generator Object A T 0x....>
In processing a large amount of data, it is best to consider the generator expression rather than the list derivation.
Another example of a list-derivation and generator expression is:
>>> data = [' abc ', ' Def ', ' I use Python ', ' hong201 ']
>>> sum ([Len (word) to Word in data])
25
>>> sum (len (word) for word in data)
25
Enumerate () is a built-in function that allows you to iterate and count at the same time, and the for loop itself can only be iterated and cannot be counted:
>>> data = [123, ABC, 3.14] >>> for
i in Enumerate (data):
... Print I ...
(0, 123)
(1, ' abc ')
(2, 3.14)