Python Learning notes-list generation and builder

Source: Internet
Author: User
Tags for in range

1. List-generation (comprehensions)

In Python, list generation is used to create lists, compared to using loops to make them more concise. For example, generate [1*1, 2*2, ..., 10*10], loop with three lines:

1 L = []2 for in range (1,11):3     l.append (i*i)

The list generation is only one row, preceded by the build rule, followed by the initial element, and finally the criteria can be added:

1  for  in range (1, 11)]

List generation can also be implemented in multi-layered loops, as well as judging, just the chestnut and then write a little more complicated:

 for inch  for inch if a==b]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

2. Generator (Generator)

List-generated list elements are limited because the list is stored in memory after all, and the generator does not need to worry about memory issues. Because the generator is saving the algorithm, compared to the list generation, the generator is time-changing space.

The generator is created in two ways:

2.1 Replace the list-generated [] with ():

1  for  in range2 >>> g3 <generator object <genexpr> at 0x104feab40>4 >>> g.next ()506 >>>  G.next ()   #遍历也可以使用for循环, without more elements, throws stopiteration error.  7 1

2.2 Using the function implementation, only need to turn the return statement into yield, in addition to the generator is the yield statement after execution stop, call the next to continue execution.

1 def fib (max): 2     N, a, b = 0, 0, 13      while n < Max:4         yield  b5
             A, B = B, A + b6         n = n + 1

Python Learning notes-list generation and builder

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.