current position:Home>Five life saving Python tips

Five life saving Python tips

2022-01-31 07:29:59 pythontip

Introduce common 5 individual python Tips , Life is too short , I use Python.

Python Is a powerful and easy to use language , The grammar is simple and elegant , Unlike Java Such tedious nonsense , And there are some special functions or syntax that can make the code shorter and more concise .

According to the author's experience , The following describes the commonly used 5 individual python Tips :

  1. String manipulation
  2. The list of deduction
  3. lambda And map() function
  4. ifelif and else Single line expression
  5. zip() function

1. String manipulation

Python Good at using mathematical operators ( Such as + and *) Operate on strings :

  • + String concatenation
  • * 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
 Copy code 

It can also be sliced [::-1] Easily invert a string , And not limited to strings ( Such as list flip )!

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]
 Copy code 

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

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

use .join() Method ,''( Space ) Connect and reverse all words in the list , And add an exclamation point !.

2. The list of deduction

5905342520623104

The list of deduction , A technique that can change your world view ! This is a very powerful 、 Intuitive and readable methods , You can quickly operate on the list .

hypothesis , There is a random function , Returns the square of a number and adds 5:

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

Now? , I want to put the function stupid_func() Applies to all odd numbers in the list , If you don't use list derivation , The stupid way 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]
 Copy code 

If you use The list of deduction , The code becomes elegant in an instant :

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]
 Copy code 

The list of deduction The grammar of :[ expression for item in list ], If you don't think it's fancy enough , You can also add a judgment condition , Like the one above " Odd number " Conditions : [expression for item in list if conditional]. Essentially, the function of the following code :

for item in list:
     if conditional:
         expression
 Copy code 

Very Cool!. But you can go further , Directly omit 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]
 Copy code 

3. Lambda & Map function

Lambda

Lambda It looks a little strange , But strange things are generally powerful , Once you master it, it's intuitive , Save a lot of nonsense code .

Basically ,Lambda Function is a small Of Anonymous functions . Why anonymous ?

because Lambda The simple operations most often used to perform , But it doesn't need to be like this def my_function() That's serious , therefore Lambda Also known as dangling function ( Fabricate , Ignore and ignore ).

Improve the above example :def stupid_func(x) You can use one line Lambda Instead of a function :

stupid_func = (lambda x : x ** 2 + 5)
print([stupid_func(1), stupid_func(3), stupid_func(5)])
#[6, 14, 30]
 Copy code 

So why use this strange Syntax ? When you want to do some simple operations without defining the actual function , This becomes very useful .

Take a list of numbers as an example . Suppose you sort the list ? One way is to use sorted() Method :

my_list = [2, 1, 0, -1, -2]
print(sorted(my_list))
#[-2, -1, 0, 1, 2]
 Copy code 

sorted() Function can complete sorting , But suppose you want to sort by the square of each number ? Available at this time lambda Function to define the sort key key, This is also 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]
 Copy code 

Map function

map yes python Built in functions , The specified sequence will be mapped according to the provided function . Suppose there is a list , Want to multiply each element in a list by the corresponding element in another list , How to do this ? Use lambda Functions and map

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

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]
 Copy code 

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")
 Copy code 

When you run a program , Prompt from input() Enter a message in the function , Such as input 5, obtain Duck. But it can also One line of code Finish the whole thing :

print("Horse" if x >= 10 else "Duck" if 1 < x < 10 else "Baguette")
 Copy code 

One line of code is simple and direct ! Look through your old code , You will find that many judgments can be reduced to one if-else Single line expression .

5. zip() function

Remember map() Are the two list elements in the function part multiplied by bits ?

zip() Make it easier . Suppose there are two lists , A contain name , A contain surname , How to merge them orderly ? 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']
 Copy code 

Section

Listed above 5 A quick tip , I hope it works for you .

If you think it's ok , Like collection , A good man is safe all his life .

pythontip Official product ,Happy Coding!

copyright notice
author[pythontip],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201310729581826.html

Random recommended