Five life saving python tips

Python is a powerful and easy-to-use language. Its syntax is concise and elegant. It is not as cumbersome and nonsense a...
1. String operation
2. List derivation
3. Lambda & map function
4. If else single line expression
5. zip() function
Section

Python is a powerful and easy-to-use language. Its syntax is concise and elegant. 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 five commonly used python tips:

  1. String operation
  2. List derivation
  3. lambda and map() functions
  4. if, elif, and else single line expressions
  5. zip() function

1. String operation

Python is good at manipulating strings with mathematical operators such as + and *:

  • +Splice string
  • *Duplicate string
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 easily reverse a string with the slice operation [:: - 1], and it is not limited to strings (such as list flipping)!

my_string = "Hi Python..!" print(my_string[::-1]) # !..nohtyP iH my_list = [1,2,3,4,5] print(my_list[::-1]) # [5, 4, 3, 2, 1]

The following is a list of words inverted and spliced into a string:

word_list = ["awesome", "is", "this"] print(' '.join(word_list[::-1]) + '!') #this is awesome!

Use the. join() method to connect and reverse all words in the list with '' (space) and add an exclamation mark!.

2. List derivation

List derivation, a skill that can change your world outlook! This is a very powerful, intuitive and readable way to quickly manipulate lists.

Suppose you have a random function that returns the square of a number plus 5:

def stupid_func(x): return x**2 + 5

Now, I want to put the function stupid_func() is applied to all odd numbers in the list. If list derivation is not used, the method is as follows:

def stupid_func(x): return x**2 + 5 my_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 deduce with a list, the code becomes elegant instantly:

def stupid_func(x): return x**2 + 5 my_list = [1, 2, 3, 4, 5] print([stupid_func(x) for x in my_list if x % 2 != 0]) #[6, 14, 30]

Syntax of list derivation: [expression for item in list]. If you think it is not fancy enough, you can also add a judgment condition, such as the above "odd" condition: [expression for item in list if conditional]. Essentially, the following code functions:

for item in list: if conditional: expression

Very Cool!. However, you can go 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]

3. Lambda & map function

Lambda

Lambda looks a little strange, but strange things are generally powerful. Once you master it, it is very intuitive and saves a lot of nonsense code.

Basically, the Lambda function is a small anonymous function. Why anonymous?

Because Lambda is most often used to perform simple operations, but it does not need to be like def my_function() is so serious that Lambda is also known as a fooling function.

Improve the above example: def stupid_func(x) can be replaced by a line of Lambda functions:

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 do something simple without defining an actual function.

Take a list of numbers as an example. Suppose you sort the list? 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 sort, but suppose you want to sort by the square of each number? In this case, the lambda function can be used to define the sorting 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 function

Map is a python built-in function that maps the specified sequence according to the provided function. Suppose you have a list and want to multiply each element in the list by the corresponding element in another list. How do you do this? Use lambda function and map!

print(list(map(lambda x, y : x * y, [1, 2, 3], [4, 5, 6]))) #[4, 10, 18]

Compared with the following conventional nonsense code, it is 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]

4. If else single line expression

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 to enter a message from the input() function, such as 5, to get Duck. But you can also do the whole thing in 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.

5. zip() function

Remember that the map() function part multiplies two list elements bit by bit?

zip() makes it easier. Suppose there are two lists, one containing the first name and the other containing the last name. How do you 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']

Section

The five quick tips listed above hope to be useful to you.

If you think it's OK, praise the collection, and a good man will live a safe life 👏.

pythontip Official product, Happy Coding!

Official account: quark programming

17 November 2021, 02:31 | Views: 2656

Add new comment

For adding a comment, please log in
or create account

0 comments