Python list derivation and builder expression __python

Source: Internet
Author: User
Tags generator python list
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)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.