18 super useful Python tips, recommended to collect!

Article source: Radish Hodgepodge

Hello everyone, I am Brother Tao. Today I will share with you 18 super useful Python tips. The full text is 5,000 words and takes 10 minutes to read.

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!

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, generally it is written 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 way to handle it is as follows:

# good practice
n1, n2, n3 = input("enter a number : ").split()
print(n1, n2, n3)

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

A 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 way to handle this is as follows:

# good practice
conditions = [
    size == "lg",
    color == "blue",
    price < 100,
]
if all(conditions):
    print("Yes, I want to but the product.")

A 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 this is as follows:

# good practice
conditions = [
    size == "lg",
    color == "blue",
    price < 100,
]
if any(conditions):
    print("Yes, I want to but the product.")

Determine parity of numbers

This is easy to implement, we get the input from the user, convert it to an integer, check the remainder operation on the number 2, if the remainder is zero, then it is an even number.

print('odd' if int(input('Enter a number: '))%2 else 'even')

Exchange variables

In Python, if we need to exchange the value of a variable, 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 way to handle it is as follows:

v1 = 100
v2 = 200
# good practice
v1, v2 = v2, v1

Determine whether a string is a palindrome string

The simplest way to reverse a string is [::-1], the code is as follows:

print("John Deo"[::-1])

Reverse a string

To determine whether a string is a palindrome string in Python, you only need to 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

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. An example is as follows, the general writing method is:

name = "ali"age = 22# bad practicesif name:print(name)if name and age > 18:print("user is verified")

But a better way to handle it 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")

Remove duplicate elements from list

We don't need to iterate through the entire 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, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0]
print(lst)
unique_lst = list(set(lst))
print(unique_lst)

Find the most repeated elements in the list

In Python, you can use the max() function and pass list.count as the key to find the most repeated element 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)

list production

My favorite feature in Python is list comprehensions. This feature allows us to write very concise and powerful code, and the code reads almost as easy to understand as natural language. Examples are 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)

Pass multiple arguments using *args

In Python we can use *args to pass multiple parameters to functions, for example:

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))

Handling subscripts while looping

Sometimes when we are working, we want to get the subscript of the element 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)

Splice multiple elements in a 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))

Merge two dictionaries

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}

Generate a dictionary using two lists

In Python, if we need to form a dictionary from corresponding elements in two lists, then we can use the zip function to do this conveniently. code show as below:

keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))

Dictionary sorted by 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)

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)))

Going a step further, we can also sort it in descending order by passing reverse=True:

sorted_d = dict(sorted(d.items(), key=itemgetter(1), reverse=True))

Pretty print

When using the Print() function in Python, sometimes the output is ugly. In this case, we can use pprint to make the output more beautiful. An example is 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': '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.

reverse list

There are generally two ways to reverse a list in Python: slicing or the reverse() function call. Both methods can reverse a list, but be aware that the built-in function reverse() changes the original list, while the slicing method creates a new list. But what about their performance? Which way is more effective? Let's look at the following example:

# 使用切片
$ python -m timeit -n 1000000 -s 'import numpy as np' 'mylist=list(np.arange(0, 200))' 'mylist[::-1]'
1000000 loops, best of 5: 15.6 usec per loop

# 使用reverse()
$ python -m timeit -n 1000000 -s 'import numpy as np' 'mylist=list(np.arange(0, 200))' 'mylist.reverse()'
1000000 loops, best of 5: 10.7 usec per loop

Both methods can reverse a list, but be aware that the built-in function reverse() changes the original list, while the slicing method creates a new list. Apparently, the built-in function reverse() is faster than the list slicing method!

干货笔记整理

  100个爬虫常见问题.pdf ,太全了!
Python 自动化运维 100个常见问题.pdf
Python Web 开发常见的100个问题.pdf

124个Python案例,完整源代码!
PYTHON 3.10中文版官方文档
耗时三个月整理的《Python之路2.0.pdf》开放下载
最经典的编程教材《Think Python》开源中文版.PDF下载

Guess you like

Origin blog.csdn.net/wuShiJingZuo/article/details/133502673