Python is a powerful and easy-to-use language with concise and elegant syntax. It is not as cumbersome and nonsense as Java, and there are some special functions or syntax that can make the code shorter and more concise. .
Based on the author’s experience, here are 5 commonly used Python tips:
Python is good at using mathematical operators (such as and *) to operate on strings: - Splicing strings - * Repeating strings
my_string = "Hi Python..!"print(my_string * 2)#Hi Python..!Hi Python..!print(my_string + " I love Python" * 2)#Hi Python..! I love Python I love Python
You can also use the slicing operation [::-1] to easily reverse a string, and it is not limited to strings (such as list flipping)!
my_string = "Hi Python..!"print(my_string[::-1])# !..nohtyP iHmy_list = [1,2,3,4,5] print(my_list[::-1])# [5, 4, 3, 2, 1]
The following is a word list that is reversed and spliced into a string:
word_list = ["awesome", "is", "this"]print(' '.join(word_list[::-1]) + '!') #this is awesome!
Use the .join() method, '' (space) to connect all the words in the reversed list, And add an exclamation point!.
List derivation, one that can change your world view Skill! This is a very powerful, intuitive and readable way to perform quick operations on lists. In addition, search the top Python background of the public account and reply "Internet of Things" to get a surprise gift package.
Suppose, there is a random function that returns the square of a number and adds 5:
def stupid_func(x): return x**2 + 5
Now, I want to apply the function stupid_func() to all odd numbers in the list. If not using a list Derivation, the stupid way is as follows:
def stupid_func(x): return x**2 + 5my_list = [1, 2, 3, 4, 5] new_list = []for x in my_list: if x % 2 != 0: new_list.append(stupid_func(x)) print(new_list)#[6, 14, 30]
If you use list derivation, the code becomes elegant instantly:
def stupid_func(x): return x**2 + 5my_list = [1, 2, 3, 4, 5] print([stupid_func(x) for x in my_list if x % 2 != 0])#[6, 14, 30]
The syntax of list derivation: [expression for item in list], if you think it is not fancy enough, you can also You can add a judgment condition, such as the "odd number" condition above: [expression for item in list if conditional]. Essentially what the following code does:
for item in list: if conditional: expression
Very Cool! . But you can go one step further and directly omit the stupid_func() function:
my_list = [1, 2, 3, 4, 5]print([x ** 2 + 5 for x in my_list if x % 2 != 0])#[6, 14, 30]
Lambda It looks a little strange, but strange things are generally very powerful and intuitive once you master them, saving a lot of nonsense code.
Basically, a Lambda function is a small anonymous function. Why anonymous?
Because Lambda is most often used to perform simple operations, but does not need to be as serious as def my_function(), so Lambda is also called a silly function (made up, ignore it).
Improve the above example: def stupid_func(x) can be replaced by a one-line Lambda function:
stupid_func = (lambda x : x ** 2 + 5) print([stupid_func(1), stupid_func(3), stupid_func(5)])#[6, 14, 30]
So why use this strange syntax? This becomes useful when you want to perform some simple operations without defining actual functions.
Take a list of numbers as an example. Suppose the list is sorted? One way is to use the sorted() method:
my_list = [2, 1, 0, -1, -2] print(sorted(my_list))#[-2, -1, 0, 1, 2]
The sorted() function can complete the sorting, but what if you want to sort by the square of each number? At this time, the lambda function can be used to define the sort key key, which is also used by the sorted() method to determine how to sort:
my_list = [2, 1, 0, -1, -2] print(sorted(my_list, key = lambda x : x ** 2))#[0, -1, 1, -2, 2]
map is a built-in function of python, which will be based on the provided function Map the specified sequence. Suppose you have a list and you want to multiply each element in the list with the corresponding element in another list. How do you do this? Use lambda functions and maps!
print(list(map(lambda x, y : x * y, [1, 2, 3], [4, 5, 6]))) #[4, 10, 18]
With the following conventional nonsense code, simple and elegant:
x, y = [1, 2, 3], [4, 5, 6] z = []for i in range(len(x)): z.append(x[i] * y[i])print(z) #[4, 10, 18]
Somewhere in your code, there may be such nonsense conditional statements:
x = int(input())if x >= 10:print("Horse") elif 1 < x < 10:print("Duck")else:print("Baguette")
When running the program, prompt from the input() function Enter a piece of information, such as 5, to get Duck. But in fact, you can also complete the whole thing with one line of code:
print("Horse" if x >= 10 else "Duck" if 1 < x < 10 else "Baguette")
One line of code is simple and direct! Looking through your old code, you will find that many judgments can be reduced to an if-else single-line expression.
Remember the map() function Partially multiply two list elements bitwise?
zip() makes it easier. Suppose there are two lists, one containing first names and one containing last names. How to merge them in order? Use zip()!
first_names = ["Peter", "Christian", "Klaus"] last_names = ["Jensen", "Smith", "Nistrup"]print([' '.join(x) for x in zip(first_names, last_names)]) #['Peter Jensen', 'Christian Smith', 'Klaus Nistrup']
The 5 quick tips listed above, I hope they are useful to you.
The above is the detailed content of Five life-saving Python tips. For more information, please follow other related articles on the PHP Chinese website!