Life is short. I use Python.

Python is a powerful and easy-to-use language with a concise and elegant syntax that is less verbose than Java, and special functions or syntax that make code shorter and more concise.

Based on my experience, here are five common Python tips:

  1. String manipulation
  2. The list of deduction
  3. lambdamap()function
  4. if,elifandelseSingle line expression
  5. zip()function

1. String operations

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

  • +Concatenated string
  • *Repeated 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 the code

It is also possible to flip a string easily with the slice operation [::-1], and 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]
Copy the code

Here is an inverted concatenation of a list of words into a string:

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

Using the.join() method, “(space) join all the words in the reverse list with an exclamation point! .

2. List derivation

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

Suppose we have a random function that returns the square of a number and adds 5:

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

Now, if you want to apply stupid_func() to all odd numbers in a list, you can do this without using a list:

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 the code

If derived from a list, the code becomes instantly elegant:

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 the code

The syntax for list derivation is [expression for item in list], and if that is not fancy enough, a conditional can be added, such as the “odd” condition above: [expression for item in list if conditional]. Essentially what this code does is:

for item in list:
     if conditional:
         expression
Copy the code

Very Cool! . The stupid_func() function can be omitted:

my_list = [1.2.3.4.5]

print([x ** 2 + 5 for x in my_list if x % 2! =0])
# [6, 14, 30]
Copy the code

3. Lambda & Mapfunction

Lambda

Lambda may seem a little strange, but strange things are usually powerful and intuitive once you get the hang of them, saving a lot of code.

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

Because Lambda is most often used to perform simple operations that do not need to be as serious as def my_function(), Lambda is also known as a “goof” function.

To improve the above example: def stupid_func(x) can be replaced with 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]
Copy the code

So why use this weird syntax? This becomes useful when you want to do something simple without having to define the actual function.

Take a list of numbers. Suppose I 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]
Copy the code

The sorted() function does this, but suppose you sort by the square of each number? We can use lambda functions to define the sorted key, which is what the sorted() method uses to decide 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 the code

The Map function

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

print(list(map(lambda x, y : x * y, [1.2.3], [4.5.6)))#[4, 10, 18]
Copy the code

Simple and elegant with regular nonsense code like this:

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 the code

4. if-elseExpress line

Somewhere in your code, you might have a conditional statement like this:

x = int(input())
if x >= 10:
    print("Horse")
elif 1 < x < 10:
    print("Duck")
else:
    print("Baguette")
Copy the code

When you run the program, you are prompted to input 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")
Copy the code

One line of code is simple and straightforward! Look through your old code and you’ll see that a lot of judgments can be reduced to an if-else single-line expression.

5. zip()function

Remember the bitwise multiplication of two list elements in the map() function?

Zip () makes it even simpler. Suppose you have two lists, one containing a first name and one containing a last name, how do you merge them in order? Use the 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 the code

section

Here are 5 quick tips that I hope will work for you.

If you feel that you can, click on the collection, good life peace 👏.

Pythontip Official, Happy Coding!