Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the 17 Python tips to improve productivity?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

What are the 17 Python skills to improve work efficiency? I believe many inexperienced people don't know what to do about it. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

1. Introduction

Next we will discuss the most commonly used python techniques. Most of these techniques are simple Trick that I have used in my daily work, and I think the good thing is to share it with you.

two。 Summary of skills 2.1. Handle multiple inputs from the user

Sometimes we need to get multiple inputs from the user in order to use a loop or any iteration, which is generally written as follows:

# bad practice code N1 = input ("enter a number:") N2 = input ("enter a number:") N2 = input ("enter a number:") print (N1, N2, n3)

But a better approach is as follows:

# good practicen1, N2, n3 = input ("enter a number:"). Split () print (N1, N2, n3) 2.2. Handle multiple conditional statements

If we need to check multiple conditional statements in our code, we can use the all () or any () function to achieve our goal. Generally speaking, we use all () when we have multiple and conditions and any () when we have multiple or conditions. This usage will make our code clearer and easier to read, making it easier for us to debug without trouble.

A general example of all () is as follows:

Size = "lg" color = "blue" price = 5cm bad practiceif size = = "lg" and color = = "blue" and price

< 100: print("Yes, I want to but the product.") 更好的处理方法如下: # good practiceconditions = [ size == "lg", color == "blue", price < 100,]if all(conditions): print("Yes, I want to but the product.") 对于any()的一般例子如下: # bad practicesize = "lg"color = "blue"price = 50if size == "lg" or color == "blue" or price < 100: print("Yes, I want to but the product.") 更好的处理方法如下: # good practiceconditions = [ size == "lg", color == "blue", price < 100,]if any(conditions): print("Yes, I want to but the product.")2.3.判断数字奇偶性 这很容易实现,我们从用户那里得到输入,将其转换为整数,检查 对数字2的求余操作,如果余数为零,则它是偶数。 print('odd' if int(input('Enter a number: '))%2 else 'even')2.4.交换变量 在Python中如果需要交换变量的值,我们无需定义临时变量来操作。 我们一般使用如下代码来实现变量交换: v1 = 100v2 = 200# bad practicetemp = v1v1 = v2v2 = temp 但是更好的处理方法如下: v1 = 100v2 = 200# good practicev1, v2 = v2, v12.5.反转字符串 将字符串进行反转最简单的实现方式为[::-1] ,代码如下: print("John Deo"[::-1])2.6.判断字符串是否为回文串 在Python中判断一个字符串是否为回文串,只需要使用语句 string.find(string[::-1])== 0 ,示 例代码如下: v1 = "madam" # is a palindrome stringv2 = "master" # is not a palindrome stringprint(v1.find(v1[::-1]) == 0) # Trueprint(v1.find(v2[::-1]) == 0) # False2.7.尽量使用 Inline if statement 大多数情况下,我们在条件之后只有一个语句,因此使用Inline if statement 可以帮助我们编写更简洁的代码。 举例如下,一般的写法为: name = "ali"age = 22# bad practicesif name: print(name)if name and age >

18: print ("user is verified")

But a better approach is as follows:

# a better approachprint (name if name else ")"here you have to define the else condition too"# good practice name and print (name) age > 18 and name and print (" user is verified ") 2.8. Delete duplicate elements in list

Instead of traversing the entire list list to check for duplicate elements, we can simply use set () to remove duplicate elements

The code is as follows:

Lst = [1,2,3,4,4,5,6,3,1,6,6,7,9,4,0] print (lst) unique_lst = list (set (lst)) print (unique_lst) 2.9. Find the most repetitive element in list

In Python, you can use the max () function and pass list.count as key to find out the most repeated elements in the list list. The code is as follows:

Lst = [1,2,3,4,4,5,6,3,6,6,6,6,7,9,4,0] most_repeated_item = max (lst, key=lst.count) print (most_repeated_item) 2.10.list generator

My favorite feature in Python is list comprehensions, which allows us to write very simple and powerful code that is almost as easy to read as a natural language.

Examples are as follows:

Numbers = [x for x in numbers if x% 2 is 0] odds = [y for y in numbers if y not in evens] cities = ['London',' Dublin', 'Oslo'] def visit (city): print ("Welcome to" + city) for city in cities: visit (city) 2.11. Use * args to pass multiple parameters

In Python, we can use * args to pass multiple parameters to the function, as an example:

Def sum_of_squares (N1, N2) return N1 so let's make it dynamic 2 + n2**2print (sum_of_squares (2Magne3)) # output: 13 "" what ever if you want to pass, multiple args to the function as n number of args. So let's make it dynamic. "" Def sum_of_squares (* args): return sum ([item**2 for item in args]) # now you can pass as many parameters as you wantprint (sum_of_squares (2,3,4)) print (sum_of_squares (2,3,4,5,6)) 2.12. Process subscripts during loops

Sometimes when we work, we want to get the subscript of the elements in the loop, generally speaking, the more elegant way to write it is as follows:

Lst = ["blue", "lightblue", "pink", "orange", "red"] for idx, item in enumerate (lst): print (idx, item) 2.13. Splicing multiple elements in list

In Python, we usually use the Join () function to stitch all the elements in list together. Of course, we can also add splicing symbols when splicing.

Examples are as follows:

Names = [john "," sara "," jim "," rock "] print (", ".join (names)) 2.14. Merge two dictionaries

In Python we can use {* * dict_name, * * dict_name2, … } merge multiple dictionaries

Examples are as follows:

D1 = {"v1": 22, "v2": 33} D2 = {"v2": 44, "v3": 55} d3 = {* * D1, * * D2} print (d3)

The results are as follows:

{'v1: 22,'v2: 44,'v3: 55}

2.15. Use two list to generate a dictionary

In Python, if we need to form a dictionary of the corresponding elements in the two lists, we can use the zip feature to easily do this.

The code is as follows:

Keys = ['await,' baked,'c'] vals = [1,2,3] zipped = dict (zip (keys, vals)) 2.16. Dictionaries are sorted by value

In Python, we use the sorted () function to sort the dictionary by its value.

The code is as follows:

D = {"v1": 80, "v2": 20, "v3": 40, "v4": 20, "v5": 10,} sorted_d = dict (sorted (d.items (), key=lambda item: item [1])) print (sorted_d)

Of course, we can also use itemgetter () to replace the above lambda function.

The code is as follows:

From operator import itemgettersorted_d = dict (sorted (d.items (), key=itemgetter (1)

Further, we can sort it in descending order by passing reverse=True:

Sorted_d = dict (sorted (d.items (), key=itemgetter (1), reverse=True) 2.17.Pretty print

Using the Print () function in Python, sometimes the output is ugly, so we can use pprint to make the output more beautiful.

Examples are as follows:

From pprint import pprintdata = {"name": "john deo", "age": "22", "address": {"contry": "canada", "state": "an state of canada:)", "address": "street st.34 north 12"}, "attr": {"verified": True, "emialaddress": True},} print (data) pprint (data)

The output is as follows:

{'name':' john deo', 'age':' 22nd, 'address': {' contry': 'canada',' state':'an state of canada:)', 'address':' street st.34 north 12'}, 'attr': {' verified': True, 'emialaddress': True}} {' address': {'address':' street st.34 north 12', 'contry':' canada' 'state':' an state of canada:)'}, 'age':' 22nd, 'attr': {' emialaddress': True, 'verified': True},' name': 'john deo'}

Use the pprint function to make the output of the dictionary easier to read.

What does python mean Python is a cross-platform, interpretive, compiled, interactive and object-oriented scripting language, originally designed to write automated scripts, and is often used to develop independent and large-scale projects as versions are constantly updated and new features are added.

After reading the above, have you mastered 17 Python tips to improve productivity? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report