Python Learning Notes (iv) List generation _ Builder

Source: Internet
Author: User

Notes excerpt from: Https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 0014317799226173f45ce40636141b6abc8424e12b5fb27000

This article is only for oneself review use, Invasion deletes;

    • List Builder
For example, listing all the file and directory names in the current directory can be implemented in one line of code: Import   for in Os.listdir ('. ')]
#[4, 16, 36, 64, 100]
 for inch if x% 2 = =

# Finally, all the strings in a list are converted to lowercase:  = ['Hello'World'IBM ' ' Apple '   for in L]   [' Hello ', ' World ', ' IBM ', ' Apple ']

    • Generator

With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted.

So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. in Python, this side loop computes the mechanism, called the generator:generator.

There are a number of ways to create a generator. The first method is simple, as long as a list of the generated formula is [] changed () to create a generator:

We can print out every element of the list directly, but how do we print out every element of generator?

If you want to print one, you can get the next return value for generator by using the next () function:

  >>> Next (g) 0  >> > next (g)  1>>> next (g)  4> >> next (g)  9>>> next (g)  16>>> next (g)  25>>> Next (g)  36>>> next (g)  49>>> 64>>> next (g)  81>>>  next (g) Traceback (most recent call last): File   " <STDIN>  , Line 1, in  <module>stopiteration    

The correct approach is to use for loops, because generator is also an iterative object:

 for  in range (ten)) for in G: ...      Print (n) ... 0149162536496481

If the calculated algorithm is more complex, and the loop with similar list generation for cannot be implemented, it can also be implemented with functions.

For example, the famous Fibonacci sequence (Fibonacci), except for the first and second numbers, can be summed up by the top two numbers:

1, 1, 2, 3, 5, 8, 13, 21, 34, ...

def fib (max):     = 0, 0, 1 while     n < Max:        yield   b              #如果一个函数定义中包含 yield keywords, Then this function is no longer a normal function, but a generator:        = b, A + b        = n + 1    return'  done'

The most difficult thing to understand here is that the generator is not the same as the execution flow of the function. The function is executed sequentially, the statement is encountered return or the last line of the function is returned. The function that becomes generator , executes at each invocation next() , encounters a yield statement return, and executes again from the last statement returned yield .

To give a simple example, define a generator and return the number 1,3,5 in turn:

def Odd ():     Print ('Step 1')     yield 1    print('step 2')    yield (3)    print('step 3')      Yield(5)

When you call the generator, you first generate a generator object, and then you next() continue to get the next return value with the function:

>>> o = odd ()>>>11>>>23>>>35>>> Next (O) Traceback (most recent):   " <stdin> "  in <module>stopiteration

As you can see, odd it is not a normal function, but a generator, which is interrupted during execution and yield continues execution the next time . After executing 3 times yield , it has not been yield able to execute, so the 4th call will be an next(o) error.

Back to fib The example, we continue to call in the loop process yield , will continue to interrupt. Of course, you have to set a condition for the loop to exit the loop, or it will produce an infinite sequence.

Similarly, after changing a function to generator , we basically never use it next() to get the next return value, but instead use the loop directly for to iterate:

 for  in fib (6): ...      Print (n) ... 112358

However for , when calling generator with a loop, the return value of the statement that is not generator is found return . If you want to get the return value, you must catch the StopIteration error, and the return value is included in StopIteration the value :

>>> g = fib (6)>>> whileTrue: ...Try: ... x=Next (g) ...Print('g:', x) ...exceptstopiteration as E: ...Print('Generator return value:', E.value) ... Break... g:1g:1g:2g:3g:5g:8GeneratorreturnValue:done

    • Yang Hui Triangle
deftriangles (): l=[1] R=[]     whiletrue:l=R R=[]         forIinchList (range (1,len (l) +2)):            if(i-1) <=0orI>Len (L): R.append (1)            Else: R.append (l[i-2]+l[i-1])        yieldR #每次执行从这里退出, the next time you execute, start from here n=0 forTinchtriangles ():Print(t) n= n + 1ifn = = 10:         Break

Python Learning Notes (iv) List generation _ Builder

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.