Python functions Advanced Features

Source: Internet
Author: User
Tags for in range iterable

Mastering the Python data types, statements, functions, can basically write a lot of useful programs. But 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. Based on this idea, let us introduce the very useful advanced features in Python, the 1 line code can be implemented without using 5 lines of code, always keep in mind that the less code, the more efficient development.

Slicing (Slice)

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

l=['micheal','Sarah','Bob', ' Jack ']

When we want to take the first n elements, it is tedious to use the loop operation, so Python provides the slicing operator, which greatly simplifies the wiping operation.

Corresponding to the above list, take the first three elements of our l[0:3] printing results [' micheal ', ' Sarah ', ' Bob '], L[0:3] means starting from index 0 until index 3, but not including index 3.

If the first index is 0 can omit L[:3], you can also start from index 1 to remove 2 elements l[1:3] output [' Sarah ', ' Bob '] similar, l[-1] output [' Jack ']

Remember that the index of the first element of the countdown is-1

Tupe is also a list, the only difference is that the tuple is immutable, so the tuple can also use the slice operation, but the result of the operation is still a tuple:

t= (0, 1, 2, 3, 4, 5)print (t[:3])# print Result: (0, 1, 2)

The string ' xxx ' can also be considered a list, each element is a character, so the string can also make the slice operation, the knowledge result is still a string

' ABCDEF ' Print (S[:3]) # print Result: ' ABC '

Iteration: If given a list or tuple, we can iterate through the for, which iterates over what we call Iteration (iteration)

When we use a For loop is, as long as the function of an iterative object, the for loop will work, and we do not care whether the object is a list or other types, then determine if an object is an iterative object, the method is judged by the iterable type of the collection module:

 from Import iterable Print (Isinstance ('abc'#  True  str can iterate print# True Print # False integer non-iterative

Python's built-in enumerate function can turn a list into an indexed element pair so that the index and the element itself can be iterated at the same time in the For loop:

 for  in Enumerate (['A','B','C'  ]):    Print (1, value) printing results 0 A1 B2 C

The above for loop, which references two variables at the same time, is very common in python, such as the following code:

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

Any object that can be iterated can be used for loops, including our custom data types, and can be used for loops as long as the criteria are met.

List Builder

The list Builder, which is comprehensions, is a very simple and powerful built-in Python build that can create a list.

For example, to generate a list [1,2,3,4,5,6,7,8,9] You can use List (range (1,11))

Print (List (range (1, one))) # printed Results [1, 2, 3, 4, 5, 6, 7, 8, 9, ten]

But what if you want to build [1x1, 2x2, 3x3, ..., 10x10] ? Method One is the loop:

L = for in range (1, one):     * x)print(L)#  Printing results: [1, 4, 9, +,----

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, 11)]

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]print(l)# Results [4, +, +, +]

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

 for inch ' ABC '  for inch ' XYZ ' ]print(l)# Prints results [' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ']< /c14>

Three-and three-storey loops are rarely used.

Using a list-generated formula, you can write very concise code. For example, listing all the file and directory names in the current directory can be implemented in one line of code:

ImportOs#Import the OS module, the concept of the modulePrint([D forDinchOs.listdir ('.')])#Os.listdir can list files and directories#Printing results:['. 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 dict the items() ability to iterate key and value at the 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'}l= [k +'='-0 forKvinchD.items ()]Print(L)#Print Results['y=b','X=a','Z=c']

Finally, all the strings in a list are converted to lowercase:

L = ['Hello',' World','IBM','Apple']ret= [S.lower () forSinchL]Print(ret)#Print Results['Hello',' World','IBM','Apple']

Python functions 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.