Python Learning-Basics (iv)

Source: Internet
Author: User

in Python, the more code is better, the less the better. The more complex the code is, the better it is, but the simpler the better.

slices:

L = [' Michael ', ' Sarah ', ' Tracy ', ' Bob ', ' Jack ']print l[0:3] # [' Michael ', ' Sarah ', ' Tracy ']


L[0:3]indicates that the fetch starts at index 0 until index 3, but does not include index 3. That is, index 0,1,2, which is exactly 3 elements. If the first index is 0, you can also print L[:3]

You can also set the step size:

L = range (+) print L[10:20:2] # The last 2 means that every 2 is a value of print L[::5] # every 5 is a print l[:] # copy One listtuple = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ten) #tuple也可以切片print tuple[:3]print ' ABCDEFG ' [: 3] # strings can also be sliced print ' ABCDEFG ' [:: 2]


The intersection from the left to the right ends, otherwise it is empty.

Iteration:

in Python, iterations areFor ... in When we use for when looping, as long as it acts on an iterative object, for The loop will work, and we're not too concerned about whether the object is a list or other data type; So, how can you tell if an object is an iterative object? The method is judged by the iterable type of the collections module:

From collections import Iterableprint isinstance (' abc ', iterable) # Trueprint isinstance ([1, 2, 3], iterable) # Trueprint Isinstance ((1, 2, 3), iterable) # Trueprint isinstance ({' Java ': ' diff ', ' Python ': ' Middle '}, iterable) # True


You can also get the subscript for an iterative object element:
For I, key in enumerate ([' A ', ' B ', ' C ']):    print i,key0 A1 b2 cfor x, y in [(1, 1), (2, 4), (3, 9)]:    print x, y1 12 43 9


List-generation:
print [x*x for x in  range (1, one-by-one)]# [1, 4, 9, 1, 2,,, Bayi, 100]print [x*x for x in range (, one) if x% ==0 ]# [4, 16, 36, 64, 100], in the list you can use the IF statement to brush the print [M+n for M in ' ABC ' for n ' XYZ ']# [' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ']l = [' Hello ', ' World ', ' Apple ', None]print [X.lower () if isinstance (x, str) Else X-in L]# [' Hel Lo ', ' world ', ' apple ', None], filtering in conditional expressions


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).

CreateLand theGThe only difference is the outermost one .[]and the(),Lis a list, andGis a generator.
s = (x*x for x in range (1, one)) print [M for M in S] # traverse the contents of generator through a for loop


Another way to generate generator:
Def odd ():    print ' Step 1 '    yield 1    print ' Step 2 '    yield 3    print ' Step 3 '    yield 5print odd () print [M For M in Odd ()]


Results:
<generator object Odd at 0x0262d3a0>step 1step 2step 3[1, 3, 5]


becomes a function of generator, after each call to theNext ()the time to execute, to encounterYieldstatement is returned, and is executed again from the last returnedYieldstatement to continue execution.

Python Learning-Basics (iv)

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.