search
HomeBackend DevelopmentPython TutorialFive life-saving Python tips

Five life-saving Python tips

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:

  • String operations
  • List derivation
  • lambda and map( ) Function
  • if, elif and else single-line expression
  • zip() function

Five life-saving Python tips

1. String operation ( https://jq../?_wv=1027&k=UEbz4NcQ)

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!.

2. List derivation (https://jq../?_wv=1027&k=UEbz4NcQ)

Five life-saving Python tips

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]

3.Lambda & Map function (https://jq../?_wv=1027&k=UEbz4NcQ)

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 function

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]

Five life-saving Python tips

4.if-else single-line expression (https://jq.com /?_wv=1027&k=UEbz4NcQ)

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.

Five life-saving Python tips

5.zip() function (https://jq..com/?_wv=1027&k=UEbz4NcQ)

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!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment