Python list derivation and generator usage analysis

  • 2020-12-05 17:17:01
  • OfStack

This article illustrates the use of Python list derivations and generators. To share for your reference, the details are as follows:

1. Look at the derivation of two lists first


def t1():
  func1 = [lambda x: x*i for i in range(10)]
  result1 = [f1(2) for f1 in func1]
  print result1
def t2():
  func2 = [lambda x, i=i: x*i for i in range(10)]
  result2 = [f2(2) for f2 in func2]
  print result2

Above are two list derivations that contain lambda Expression. The output results are as follows:

[

[18, 18, 18, 18, 18, 18, 18, 18, 18, 18]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

]

2. Why are the results different

In the above example, list parsing produces a series 1 function object. For example,


def func():
  pass

A function object named func is generated. Notice is different from func() With the parenthesis, it becomes a calling function object.

Function objects begin referencing internal variables only when they are called. in t1() In the method, for i, when the function references it, it has become 9, so all 10 functions are referenced i=9 .

And for t2() In terms of methods, lambda The function takes two arguments, so it returns a different result.

3. Another way


def t3():
  func3 = (lambda x: x*i for i in range(10))
  result3 = [f3(2) for f3 in func3]
  print result3

Above code, the output result is:

[

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

]

At this point, you turn the list derivation into a generator, and the result is not the same!

For generator, only when you need it, this is the list and the analytic expression, the difference between a list of analytic expression as long as you run, immediately turn i into 9, the generator will not, however, when you call the first function, he put the corresponding i out, then stop, wait for you under one call, this is perfectly in line with our expectations.

For more information about Python, please refer to Python list (list) operation Skills Summary, Python String operation skills Summary, Python Data Structure and Algorithm Tutorial, Python Function Use Skills Summary, Python Introduction and Advanced Classic Tutorial and Python File and Directory Operation Skills Summary.

I hope this article has been helpful in Python programming.


Related articles: