Python Advanced Features

Source: Internet
Author: User

Slice

Taking a list or tuple element is a very common operation. For example, a list is as follows:

>>> L = ['Michael'Sarah'Tracy ' ' Bob ' ' Jack ']

What should I do if I take the first 3 elements? Python provides a slicing (Slice) operator that can greatly simplify this operation.

>>> l[0:3['Michael'Sarah ' Tracy ']

L[0:3]Represents, starting from the index, until the index 0 3 , but not 3 including the index. That is 0 1 2 , an index, which is exactly 3 elements.

If the first index is 0 , you can also omit:

>>> l[:3['Michael'Sarah ' Tracy ']

Support for reciprocal slices: ( the index of the first element -1 to the bottom is )

>>> l[-2: ['Bob'Jack']> >> l[-2:-1['Bob']

Slicing operations are useful. Let's start by creating a 0-99 series:

>>> L = list (range)>>>1, 2, 3, ..., 99]

First 10 numbers:

>>> l[:101, 2, 3, 4, 5, 6, 7, 8, 9]

10 Number of second:

>>> l[-10: [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

Number of first 11-20:

>>> l[10:20[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

First 10 numbers, each of two fetch one:

>>> l[:10:22, 4, 6, 8]

All numbers, fetch one per 5:

>>> l[::55, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

Do not write anything, just write [:] it can copy a list:

>>>1, 2, 3, ..., 99]

Tuple is also a list, the only difference is that the tuple is immutable. Therefore, a tuple can also be used for slicing operations, but the result of the operation is still a tuple:

>>> (0, 1, 2, 3, 4, 5) [: 31, 2)

A string ‘xxx‘ can also be seen as a list, with each element being a character. Therefore, a string can also be manipulated with a slice , but the result of the operation is still a string:

' ABCDEFG ' [: 3] ' ABC ' ' ABCDEFG ' [:: 2] ' Aceg '

Python does not have an intercept function for a string, it can be done simply by slicing one operation.

Iteration

Given a list or tuple, we can iterate through the list or tuple through a for loop , which we call an iteration (iteration). In Python, iterations are done through for ... in .

The Python for loop can be used not only on a list or tuple, but also on other iterative objects .

List this data type although there is subscript, but many other data types are not subscript, but as long as the object can be iterated, whether or not subscript, can iterate , such as dict can iterate:

>>> d = {'a'b' 'C': 3 } for in D: ...      Print (Key) ... ACB

By default, the Dict iteration is key. If you want to iterate over value, you can use for value in d.values() it if you want to iterate both key and value at the same time for k, v in d.items()  .

Because a string is also an iterative object, it can also be used for for loops :

 for inch ' ABC ' :...      Print (CH) ... ABC

So, when we use for a loop, the loop works as long as it works on an iterative object, for and we don't care much about whether the object is a list or another 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 Import iterable>>> isinstance ('abc'#  str can iterate True  #  Whether the list can iterate True#  integer Whether it can iterate False

forIn the loop, two variables are referenced at the same time, which is common in Python:

 for inch [(1, 1), (2, 4), (3, 9)]: ...      Print (x, y) ... 1 12 43 9

List-Generated

What do i [1x1, 2x2, 3x3, ..., 10x10]  do if I want to build? Method One is the loop:

>>> L = [] for in range (1, one): ...     . * x) ... >>> l[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

But the loop is too cumbersome, and the list generation can use a line of statements instead of loops to generate the list above:

 for  in range (1, one) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

When writing list generation, put the elements to be generated in x * x front , followed by the for loop , you can create a list , very useful, write a few more times, you can quickly become familiar with this syntax.

The For loop can also be followed by an if judgment so that we can filter out only the even squares:

 for inch if x% 2 = = 0][4, 16, 36, 64, 100]

You can also use a two-layer loop to generate a full array :

>>> [M + N forMinch 'ABC'  forNinch 'XYZ']['AX','AY','AZ','BX',' by','BZ','CX','CY','CZ']

Lists all file and directory names under the current directory, which can be implemented in one line of code:

>>>ImportOs#Import the OS module, the concept of the module>>> [D forDinchOs.listdir ('.')]#Os.listdir can list files and directories['. EMACS.D','. SSH','. Trash','ADLM','Applications','Desktop','Documents','Downloads','Library','Movies','Music','Pictures',' Public','VirtualBox VMs','Workspace','XCode']

forLoops can actually use two or more variables at the same time, such as the ability to iterate key and valueat dict the items() same time:

>>> d = {'x':'A','y':'B','Z':'C' }>>> forKvinchd.items(): ...PrintK'=', v) ... y=Bx=Az= C

As a result, list generators can also use two variables to generate lists:

>>> d = {'x':'A','y':'B','Z':'C' }>>> [k +'='-0 forKvinchD.items ()] ['y=b','X=a','Z=c']

To turn all the strings in a list into lowercase:

>>> L = ['Hello',' World','IBM','Apple']>>> [S.Lower() forSinchL] ['Hello',' World','IBM','Apple']

Python Advanced Features

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.