Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the important Python skills?

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the important Python skills". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. Exchange of variables

A = 1 b = 2 if we need to exchange the contents of an and b, we can usually define a temporary variable tmp tmp = an a = b b = tmp

First store the contents of an in it, then set a to b, and then set b to this temporary variable

But the above code can actually be rewritten like this in Python: in this way, the readability of the program is greatly improved.

A = 1 b = 2 a, bb = b, a

II. Formatting of strings

Name = "Chan" print ("Hi, Isimm" + name)

Usually, if we need to combine or concatenate strings in the program, we use the plus sign to concatenate the strings. If we do the concatenation of two strings, there is no problem with this, but if there are more strings, it is similar to this:

Name = "Chan" country = "China" age = 23 print ("Hi, Ichimm" + name + ".Ihumm from" + country + ".And Isimm" + str (age) + "."

Such a program will be very messy and difficult to read; moreover, when we connect plastic data, we also need to convert the type, otherwise the program will report an error.

In fact, we can write the program like this and use the% sign syntax of Python to format the string, where% s represents a string that will be replaced here,% d means that it will be replaced with a decimal system, and finally, the content in the brackets represents the content that will be replaced:

Name = "Chan" country = "China" age = 23 print ("Hi, Isimm% s. Isimm from% s. And Isimm% d."% (name,country,age))

Although the program looks much better like this, we can do better here. We can use the format function and curly braces syntax in python to write the program like this:

The contents of the curly braces will be replaced with the parameters passed in the format function

Name = "Chan" country = "China" age = 23 print ("Hi, Ihumm {}. ITunm from {}. And Isimm {}." .format (name,country,age))

The contents of the curly braces will be replaced with the parameters passed in the format function. The benefits of using this function are:

You can write the replaced index in curly braces, and the place of the same index will be replaced with the same content, like this:

Name = "Chan" print ("Hi, Isimm {0}. And Isimm {0}." .format (name)) result: Hi, Ichimm Chan. And I'm Chan

The last one, and my favorite, is called f-string. We just need to write an f at the beginning of the string, and the contents of the curly braces are automatically replaced with the value of the specified expression. Note that it is the expression:

Name = "Chan" country = "China" age = 23 print (f "Hi, iTunm {name}. ITunm from {country}. And isimm {age+1}."

Third, Yield grammar in Python

For example, here we define a fibonacci () function that enumerates the first n digits of the Fibonacci sequence: 0, 1, 1, 2, 3, 5.

Def fibonacci (n): a = 0b = 1 nums = [] for _ in range (n): nums.appends (a) a, bb = b, axib return nums for i in fibonacci (10): print (I)

We can modify the fibonacci () function to use the yield syntax in Python:

First, rewrite append into yield.

Then delete the num list

In this way, the program will be the same as above, yield a says, every time we calculate an element, we send it out immediately; we don't need to wait for the whole list to be generated before outputting it; the advantage of yield is that it outputs in time in some very time-consuming operations.

Def fibonacci (n): a = 0 b = 1 for _ in range (n): yield an a, bb = b, aquib return nums for i in fibonacci (10): print (I)

Fourth, list analytical formula

For example, we have a series of fruit names, which are stored in the fruit list. If we want to change the contents of the list to uppercase, we can do it in many ways:

Fruit = ["apple", "pear", "orange", "banana"] the first: for i in range (len (fruit)): fruit [I] = fruit.upper () the simpler syntax: fruit = [x.upper for x in fruit]

What follows for in square brackets tells python that we need to enumerate all the elements in the fruit variable, where each element's name is x, and the first half capitalizes x upper ().

To do an exercise, the comments section can tell you what this code means:

Fruit = ["apple", "pear", "orange", "banana"] new_fruit = [x for x in fruit if x.startwith ("a")]

Five: Enumerate function

Using the example of 4, we want to output all the elements in a list sequentially, we can use the following ways:

Fruit = ["apple", "pear", "orange", "banana"] for x in fruit: print (x)

If we want to get the index value for each value pair, for example, apple is 0 and apple is 2, we can use the Enumerate function to change the program like this:

Fruit = ["apple", "pear", "orange", "banana"] for iMagne x in enumerate (fruit): print (iMagne x) I is the index value, x is the content value

VI. Reverse traversal

What should we do if we want to output the list from back to front?

Actually, all you have to do is add the reversed function:

Fruit = ["apple", "pear", "orange", "banana"] for iMagne x in enumerate (reversed (fruit)): print (iMagne x)

To output fruit elements in alphabetical order, use the sorted function:

Fruit = ["apple", "pear", "orange", "banana"] for iMagne x in enumerate (sorted (fruit)): print (iMagne x)

VII. Merge operation of dictionaries

For example, we have two dictionaries that store different user names and passwords. We can write a program to merge the two dictionaries:

A = {"ross": "123456", "xiaoming": "xiao123"} b = {"lili": "11111", "nana": "123456"} c = {} for k in a: C [k] = a [k] for k in b: C [k] = b [k]

We can rewrite the program to:

A = {"ross": "123456", "xiaoming": "xiao123"} b = {"lili": "11111", "nana": "123456"} c = {* * a, * * b}

The two * * numbers are called unpacking unpacking in python, meaning to put the contents of an and b directly into c

8. Ternary operator:

We often set variables to different values according to conditions:

If score > 60: s = "pass" else: s = "fail"

In fact, it can be changed directly to:

S = "pass" if score > 60 else "fail"

The if...else here is called the ternary operator in Python

IX. Sequence unpacking

We define a variable and store the first and last names of the first names. If we want to extract their first and last names separately and store them in different variables, our easiest way is to use the split () function:

Name = "Xiao Chen" str_list = name.split () first_name = str_list [0] last_name = str_list [1]

In fact, this code can be rewritten as:

Name = "Xiao Chen" first_name,last_name = name.split ()

We directly assign the elements in the list returned by the split () function to first_name and last_name. This operation is called sequence unpacking in python, where the sequence is not necessarily a list, it can be a tuple, or even a range.

10. With statement

If we want to open a file, we can use the open function to open and read the file

Don't forget to close the file after reading. If not, Python will occupy the resources of the file until the program exits.

F = open ("suchfils.txt", "r") s = f.read () f.close ()

For small scripts, this is not a big deal, but for a program that runs on the server for a long time, the system resources are likely to be eaten up and the system program will crash; so it is a better habit to use Python's with statement to rewrite the program as follows:

With open ("suchfils.txt", "r") as f: s = f.read ()

In this way, there is no need to call the close function. After execution, the file will be closed automatically.

This is the end of "what are the important Python skills"? thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report