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 more
Short and sharp . According to my experience , The following describes the commonly used 5 individual Python Tips :
• String manipulation
• The list of deduction
•lambda And map() function
•if、elif and else Single line expression
•zip() function
###python####
python Exchange of learning Q Group :903971231####
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
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 iHmy_list = [1,2,3,4,5]
print(my_list[::-1])# [5, 4, 3, 2, 1]
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!
use .join() Method ,‘’( Space ) Connect and reverse all words in the list , And add an exclamation point !.
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
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 + 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 a list to derive , The code becomes elegant in an instant :
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]
Syntax for list derivation :[ 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
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]
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 anonymous function . 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
Of , 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]
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]
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]
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]
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 you run a program , Prompt from input() Enter a message in the function , Such as input 5, obtain Duck. But it can also be done 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 ! Look through your old code , You will find that many judgments can be reduced to one if-else Single line expression .
Remember map() Are the two list elements in the function part multiplied by bits ?
zip() Make it easier . Suppose there are two lists , An include name , One with last name , 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']
Listed above 5 A quick tip , I hope it works for you . See you in the next chapter !!!