Python list generative and generator learning tutorial, python generative

Source: Internet
Author: User

Python list generative and generator learning tutorial, python generative

List Generator
That is, the method for creating a list. The most stupid method is to generate a write loop one by one. The range () function can also be used to generate a list, but only a linear list can be generated, the following describes more advanced generation methods:

>>> [x * x for x in range(1, 11)][1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

When writing the list generator, put the x element to be generated in front, followed by the for loop, you can create the list, which is very useful and can be written several times more, you will soon be familiar with this syntax.
You can even add the if statement to the end:

>>> [x * x for x in range(1, 11) if x % 2 == 0][4, 16, 36, 64, 100]

Loop nesting, full arrangement:

>>> [m + n for m in 'ABC' for n in 'XYZ']['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

Check a simple application to list all files and directories under the current directory:

>>> import os>>> [d for d in os.listdir('.')]['README.md', '.git', 'image', 'os', 'lib', 'sublime-imfix', 'src']

As mentioned above, two variables can be referenced in a loop in Python at the same time, so the variable can also be generated:

>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }>>> [k + '=' + v for k, v in d.iteritems()]['y=B', 'x=A', 'z=C']

You can also use a list to generate another list. For example, you can change all strings in a list to lowercase:

>>> L = ['Hello', 'World', 'IBM', 'Apple']>>> [s.lower() for s in L]['hello', 'world', 'ibm', 'apple']

However, there is a problem here. If there are other non-string types in the list, lower () will report an error. solution:

>>> L = ['Hello', 'World', 'IBM', 'Apple', 12, 34]>>> [s.lower() if isinstance(s,str) else s for s in L]['hello', 'world', 'ibm', 'apple', 12, 34]

In addition, the list generation method has many magical usage. For more information, see the notes:

#! /Usr/bin/env python3 #-*-coding: UTF-8-*-list (range (1, 11) # generate 1 by 1, 2 by 2... 10 multiplied by 10 L = [] for x in range (1, 11): L. append (x * x) # It is too troublesome. See [x * x for x in range (1, 11)] # [1, 4, 9, 16, 25, 36, 49, 64, 81,100] # Add if to filter out the even square [x * x for x in range (1, 11) if x % 2 = 0] # [4, 16, 36, 64,100] # Two-layer loop, [m + n for m in 'abc' for n in 'xyz'] # ['ax ', 'ay', 'az', 'bx ', 'by', 'yz', 'cx ', 'cy', 'cz '] # list all files and directory names in the current directory import OS [d for d in OS. listdir ('. ')] # on. listdir can be used to list files and directories # generate A list or use two variables to generate A list: d = {'X': 'A', 'y': 'B ', 'Z': 'C'} [k + '=' + v for k, v in d. items ()] # ['X = A', 'z = C', 'y = B '] # convert all strings in A list to lowercase L = ['hello ', 'World', 'ibm ', 'apple'] [s. lower () for s in L] # ['hello', 'World', 'ibm, 'apple'] L1 = ['hello', 'World', 18, 'apple', None] L2 = [s. lower () for s in L1 if isinstance (s, str)] print (L2) # ['hello', 'World ', 'apple'] # The isinstance function can determine whether a variable is a string.

Generator
The list generation method is powerful, but it also has a problem. When we want to generate a large list, it will take a lot of time and occupy a lot of storage space, the key is that you may only need to use a small part of the above elements, and most of the space and time are wasted. Python provides a mechanism for edge computing and edge usage. It is called a Generator. The simplest way to create a Generator is to change [] ():

>>> g = (x * x for x in range(10))>>> g<generator object <genexpr> at 0x7fe73eb85cd0>

To print them one by one, you can use the next () method of generator:

>>> g.next()0>>> g.next()1>>> g.next()4>>> g.next()9>>> g.next()16>>> g.next()25>>> g.next()36>>> g.next()49>>> g.next()64>>> g.next()81>>> g.next()Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration

In fact, the generator object can be iterated, so it can be printed cyclically without any error.

>>> g = (x * x for x in range(10))>>> for n in g:...   print n...

This is a simple algorithm, but if the algorithm is complicated, it is not appropriate to write it in (). We can use a function to implement it in another way.
For example, in the famous onacci series, except for the first and second numbers, any number can be obtained by adding the first two numbers:
1, 1, 2, 3, 5, 8, 13, 21, 34 ,...
The Fibonacci series cannot be written in the form of list generation, but it is easy to print it out using functions:

def fib(max):  n, a, b = 0, 0, 1  while n < max:    print b    a, b = b, a + b    n = n + 1

The above function can output the first N number of the Fibonacci series. This is also calculated based on the previous number, so we can convert the function into a generator object, you only need to change print B to yield B.

def fib(max):  n, a, b = 0, 0, 1  while n < max:    yield b    a, b = b, a + b    n = n + 1

If a function definition contains the yield keyword, this function is not a common function, but a generator object.

>>> fib(6)<generator object fib at 0x7fa1c3fcdaf0>>>> fib(6).next()1

Therefore, to call this function, you need to use the next () function and return the yield Statement (yield can be understood as return ):

def odd():  print 'step 1'  yield 1  print 'step 2'  yield 3  print 'step 3'  yield 5

Check the call output result:

>>> o = odd()>>> o.next()step 11>>> o.next()step 23>>> o.next()step 35>>> o.next()Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration

You can also change it to for loop statement output. For example:

def odd():  print 'step 1'  yield 1  print 'step 2'  yield 2  print 'step 3'  yield 3if __name__ == '__main__':  o = odd()  while True:    try:      print o.next()    except:      break

Articles you may be interested in:
  • An example is provided to illustrate the usage of the list Data Structure in Python.
  • How to convert a list into a dictionary data structure using Python
  • Python generator expression and list Parsing
  • Reverse, sort, and sorted
  • Example of how to sort tuples and lists by conditions in Python
  • A preliminary understanding of list and bitwise operators in Python
  • Differences between list generators and generators in Python
  • Differences between extend and append in python list operations
  • How to append an element to a list in python
  • Comparison of map and list derivation efficiency in Python
  • Python calls function instances using the ancestor and list through apply
  • In-depth analysis of list and its slicing and iteration operations in Python

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.