17 useful Python tips to share!
Text
Hello everyone, I am Python artificial intelligence technology.
In this article, we will discuss the most commonly used python tricks. Most of these techniques are simple Tricks that I use in my daily work, and I think good things should be shared with everyone.
Without further ado, let’s get started! :)
Tips summary
1. Handling multiple inputs from the user
Sometimes we need to get multiple inputs from the user in order to use a loop or any iteration, generally The writing method is as follows:
# bad practice码 n1 = input("enter a number : ") n2 = input("enter a number : ") n2 = input("enter a number : ") print(n1, n2, n3)
But a better processing method is as follows:
# good practice n1, n2, n3 = input("enter a number : ").split() print(n1, n2, n3)
2. Processing multiple conditional statements
If we need to check multiple conditional statements in the code, At this point we can use the all() or any() function to achieve our goal. Generally, all() is used when we have multiple and conditions and any() is used when we have multiple or conditions. This usage will make our code clearer and easier to read, and will help us avoid trouble when debugging.
The general example for all() is as follows:
size = "lg" color = "blue" price = 50 # bad practice if size == "lg" and color == "blue" and price < 100: print("Yes, I want to but the product.")
A better processing method is as follows:
# good practice conditions = [ size == "lg", color == "blue", price < 100, ] if all(conditions): print("Yes, I want to but the product.")
The general example for any() is as follows:
# bad practice size = "lg" color = "blue" price = 50 if size == "lg" or color == "blue" or price < 100: print("Yes, I want to but the product.")
A better way to handle it is as follows:
# good practice conditions = [ size == "lg", color == "blue", price < 100, ] if any(conditions): print("Yes, I want to but the product.")
3. Determine number parity
This is easy to implement, we get the input from the user, convert it to an integer, check for the number 2 The remainder operation of , if the remainder is zero, it is an even number.
print('odd' if int(input('Enter a number: '))%2 else 'even')
4. Exchange variables
If we need to exchange the value of a variable in Python, we do not need to define a temporary variable to operate. We generally use the following code to implement variable exchange:
v1 = 100 v2 = 200 # bad practice temp = v1 v1 = v2 v2 = temp
But a better processing method is as follows:
v1 = 100 v2 = 200 # good practice v1, v2 = v2, v1
5. Determine whether the string is a palindrome string
Change the characters The simplest way to reverse a string is [::-1], the code is as follows:
print("John Deo"[::-1])
6. Reverse a string
Determine whether a string is a palindrome in Python String, just use the statement
string.find(string[::-1])== 0, the sample code is as follows:
v1 = "madam" # is a palindrome string v2 = "master" # is not a palindrome string print(v1.find(v1[::-1]) == 0) # True print(v1.find(v2[::-1]) == 0) # False
7. Try to use Inline if statement
Most of the time, we only have one statement after the condition, so using Inline if statement can help us write more concise code. For example, the general writing method is:
name = "ali" age = 22 # bad practices if name: print(name) if name and age > 18: print("user is verified")
But a better processing method is as follows:
# a better approach print(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")
8. Delete duplicate elements in the list
We don’t need to traverse the entire list List to check for duplicate elements, we can simply use set() to delete duplicate elements, the code is as follows:
lst = [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0] print(lst) unique_lst = list(set(lst)) print(unique_lst)
9. Find the most repeated elements in the list
You can use max in Python ( ) function and pass list.count as key, you can find the element with the most repetitions in the list. The code is as follows:
lst = [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0] most_repeated_item = max(lst, key=lst.count) print(most_repeated_item)
10. List generation
My favorite in Python The function of List Comprehension is list comprehensions. This feature allows us to write very concise and powerful code, and these codes read almost as easy to understand as natural language. An example is as follows:
numbers = [1,2,3,4,5,6,7] evens = [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)
11. Use *args to pass multiple parameters
In Python, we can use *args to pass multiple parameters to a function. An example is as follows:
def sum_of_squares(n1, n2) return n1**2 + n2**2 print(sum_of_squares(2,3)) # 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 want print(sum_of_squares(2, 3, 4)) print(sum_of_squares(2, 3, 4, 5, 6))
12. Processing subscripts during loops
Sometimes when we are working, we want to get the subscripts of elements in the loop. Generally speaking, the more elegant way of writing is as follows:
lst = ["blue", "lightblue", "pink", "orange", "red"] for idx, item in enumerate(lst): print(idx, item)
13. Splicing multiple elements in the list
In Python, the Join() function is generally used to splice all the elements in the list together. Of course, we can also add splicing symbols when splicing. The example is as follows:
names = ["john", "sara", "jim", "rock"] print(", ".join(names))
14. Merge the two dictionaries
In addition, search the top Python background of the public account and reply "Advanced" to get a surprise gift package.
In Python we can use {**dict_name, **dict_name2, …} to merge multiple dictionaries. The example is as follows:
d1 = {"v1": 22, "v2": 33} d2 = {"v2": 44, "v3": 55} d3 = {**d1, **d2} print(d3)
The result is as follows:
{'v1': 22, 'v2': 44, 'v3': 55}
15 Use two lists to generate a dictionary
In Python, if we need to combine the corresponding elements in the two lists into a dictionary, then we can use the zip function to easily do this. The code is as follows:
keys = ['a', 'b', 'c'] vals = [1, 2, 3] zipped = dict(zip(keys, vals))
16. Sort the dictionary according to value
In Python we use the sorted() function to sort the dictionary according to 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) 当然我们也可以使用itemgetter( )来替代上述 lambda函数,代码如下: from operator import itemgetter sorted_d = dict(sorted(d.items(), key=itemgetter(1)))
Further, we can also sort it in descending order by passing reverse=True:
sorted_d = dict(sorted(d.items(), key=itemgetter(1), reverse=True))
17, Pretty print
Using the Print() function in Python, sometimes the output It's ugly. At this time, we can use pprint to make the output more beautiful. The sample is as follows:
from pprint import pprint data = { "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': '22', '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': '22', 'attr': {'emialaddress': True, 'verified': True}, 'name': 'john deo'}
It can be seen that using the pprint function can make the output of the dictionary easier to read.
The above is the detailed content of 17 useful Python tips to share!. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.
