Introduction: Whether you are a beginner or an experienced developer, these tips can help you better use Python to solve problems, increase efficiency, and write cleaner, maintainable code. Whether you're a data scientist, web developer, automation scripter, or someone else, these tips can help.
Table of contents
Handle multiple inputs from the user
Handle multiple conditional statements
Determine whether a string is a palindrome string
Two lists generate a dictionary
Remove duplicate elements from list
Find the most repeated elements in the list
Splicing multiple elements in list
Handle multiple inputs from the user
Sometimes we need to get multiple inputs from user so use loop or any iteration
# bad
n1 = input("请输入 : ")
n2 = input("请输入 : ")
n2 = input("请输入 : ")
print(n1, n2, n3)
If the user is typing with a delimiter, such as a comma or semicolon, you can pass the delimiter as a split
method argument. For example, if the user separates words with commas, you could handle it like this:
# good
user_input = input("请输入多个单词,用空格分隔:")
words = user_input.split()
print("你输入的单词是:")
for word in words:
print(word)
Handle multiple conditional statements
age= 18
price = 50
# bad
if age== 18 and price < 100:
print("Yes")
If we need to check multiple conditional statements in our code, we can use 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.
# good
conditions = [
age == 18,
price < 100,
]
if all(conditions):
print("Yes")
If one of the conditions is met, we can also use any()
# good
conditions = [
age == 18,
price < 100,
]
if any(conditions):
print("Yes")
Exchange variables
This is a bit cliché. Python’s unique mechanism makes it possible to convert variables without intermediate variables.
# bad
temp = v1
v1 = v2
v2 = temp
Instead, it can be exchanged directly:
# good
v1, v2 = v2, v1
Determine whether a string is a palindrome string
One way to make this determination is to compare whether it is the same as its inverse. If they are the same, then the string is a palindrome
The simplest way to reverse a string is [::-1], for example:
print("aaahhhaaabbb"[::-1])
Then just try to find if there is a flipped string in the original string, because the lengths are equal, and if found, it must be itself.
v1 = "asdfdsa"
v2 = "master er"
print(v1.find(v1[::-1]) == 0) # True
print(v1.find(v2[::-1]) == 0) # False
Tips: find() is used to find the first occurrence of a substring in a given string. If the substring is found, it returns the starting index of the substring; if not found, it returns -1.
Pretty print
When processing JSON or XML data, Pretty Print can format it in an easy-to-read manner, and can also automatically format the code to make it comply with programming specifications and style guides, improving the readability of the code.
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)
Take a look at the results:
{'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'}
Two lists generate a dictionary
If we need to form a dictionary from corresponding elements in two lists, then we can use the zip function to do this
keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))
print(zipped)
# {'a': 1, 'b': 2, 'c': 3}
Merge two dictionaries
You can use {**dict_name, **dict_name2, … } to merge multiple dictionaries
d1 = {"v1": 22, "v2": 33}
d2 = {"v2": 44, "v3": 55}
d3 = {**d1, **d2}
print(d3)
# {'v1': 22, 'v2': 44, 'v3': 55}
Remove duplicate elements from list
We don't need to loop through the entire list to check for duplicate elements, we can simply use set() to remove duplicate elements
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 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)
list production
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.
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 = ['beijing', 'shanghai', 'tianjin']
print(evens)
print(odds)
for city in cities:
print("Welcome to "+city)
# 结果
[2, 4, 6]
[1, 3, 5, 7]
Welcome to beijing
Welcome to shanghai
Welcome to tianjin
Using subscripts in loops
If you want to get the subscript of the element in the loop in a loop, generally speaking, the more elegant way to write it is to use enumerate . The code is as follows:
lst = ["blue", "yellow", "pink", "orange", "red"]
for idx, item in enumerate(lst):
print(idx, item)
# 结果
0 blue
1 yellow
2 pink
3 orange
4 red
Splicing multiple elements in list
Use the join() function to add splicing characters to splice all elements in the list together.
names = ["aaa", "bbb", "ccc", "ddd", "eee"]
print(", ".join(names))
# aaa, bbb, ccc, ddd, eee
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.
import numpy as np
mylist=list(np.arange(0, 200))
mylist[::-1]
# 15.6 usec per loop
mylist.reverse()
# 10.7 usec per loop
Obviously, the built-in function reverse() is faster than the list slicing method
I hope these tips can provide you with some new ideas or motivation to keep learning.
Welcome to collect, comment and exchange, please indicate the source when reprinting.
-----------------------
2023.09.25