Station B|Official account: a graduate student who knows everything
Related Reading
These seven 100% performance-improving Python code performance skills must be known. I
have sorted out a few Python detail pits that 100% will step on to prevent cerebral thrombosis in advance.
I have sorted out ten 100% efficient Python programming skills to improve
Python-list, from basic to advanced usage summary, come in to check
and fill in
gaps Big summary, come in to check and fill in the gapsPython
-collection, from basic to advanced Big summary, come in to check for leaks and fill in the gaps.
These bad habits of Python programming, including mine, get rid of the
pits of Python variable types as soon as possible, and don’t step on
the list anymore Comprehensions, the best feature in Python? readability?
Isn't a tuple just an immutable list?
Subscribe to the column ===> Python
Hello, I am a student of everything. In this article, I will introduce 17 Python programming cases with a lot of room for improvement. Now that Python is used, the provided wheels should be used quickly. Haha, let’s take a look~
1. Use multiple print statements
Beginner
If you want to print multiple variables, some people think that each variable should have its own print()
statement , hahaha I used to be the same
a, b, c = 10, 5, 3
print(a)
print(b)
print(c)
# 10
# 5
# 3
Advanced
Using multiple print statements is the most common mistake made by newcomers especially when coding in Python. In fact, print()
you can print multiple variables in a single print statement, as follows:
a, b, c = 10, 5, 3
print(a, b, c, sep = "\n")
# 10
# 5
# 3
The above sep
parameter specifies the delimiter between the various variables printed using the same print statement (above a
, b
andc
Note that
end
the parameter is used to specify the terminator of the print statement
a, b, c = 10, 5, 3
print(a, end = "\n---\n")
print(b, end = "\n---\n")
print(c)
# 10
# ---
# 5
# ---
# 3
In the code above, end='\n---\n'
the argument prints a newline, then a newline ---
, then a newline
2. Use the Print statement instead of the logging module
It may not matter in small projects, I also like print, but it is worth mentioning that logs are too important in large projects
primary
>>> print('This is a warning message')
# This is a warning message
>>> print('This is an error message')
# This is an error message
>>> print('This is a critical message')
# This is a critical message
Advanced
>>> import logging
>>> logging.warning('This is a warning message')
# WARNING:root:This is a warning message
>>> logging.error('This is an error message')
# ERROR:root:This is an error message
>>> logging.critical('This is a critical message')
# CRITICAL:root:This is a critical message
3. Use a for loop to print the same variable
primary
As the title says, our goal is to print the same variable multiple times
Of course, create a for loop to print, can you say that there is a problem, of course there is no problem
repeat = 10
a = "ABC"
for _ in range(repeat):
print(a, end = "")
# ABCABCABCABCABCABCABCABCABCABC
Advanced
Although there is no harm in writing a for loop, it is not necessary, it can be like this
repeat = 10
a = "ABC"
print(a*repeat)
# ABCABCABCABCABCABCABCABCABCABC
4. Create a separate variable to keep track of the index in the loop
Elementary - 1
To achieve this, it is common to define a new variable idx
to keep track of the index value and increment it on each iteration, like so:
idx = 0
char_list = ["a", "b", "c", "d", "e", "f"]
for i in char_list:
print("index =", idx, "value =", i, sep = " ")
idx += 1
# index = 0 value = a
# index = 1 value = b
# index = 2 value = c
# index = 3 value = d
# index = 4 value = e
# index = 5 value = f
Elementary - 2
Alternatively, create an range
iterator to keep track of the index, as follows:
char_list = ["a", "b", "c", "d", "e", "f"]
for idx in range(len(char_list)):
print("index =", idx, "value =", char_list[idx], sep = " ")
idx += 1
# index = 0 value = a
# index = 1 value = b
# index = 2 value = c
# index = 3 value = d
# index = 4 value = e
# index = 5 value = f
Advanced
I have to mention enumerate()
the method, using this method, you can keep track of the index idx
and value i
, as follows:
char_list = ["a", "b", "c", "d", "e", "f"]
for idx, i in enumerate(char_list):
print("index =", idx, "value =", i, sep = " ")
# index = 0 value = a
# index = 1 value = b
# index = 2 value = c
# index = 3 value = d
# index = 4 value = e
# index = 5 value = f
5. Use a for loop to convert the list to a string
primary
As shown below, use a for loop to stitch one element in the list at a time
char_list = ["A", "B", "C", "D", "E"]
final_str = ""
for i in char_list:
final_str += i
print(final_str)
# ABCDE
Advanced
Actually an easy way to convert a list to a string is to use join()
the method , like so:
char_list = ["A", "B", "C", "D", "E"]
final_str = "".join(char_list)
print(final_str)
# ABCDE
Not only does this save you from writing some unnecessarily long code, but it's as intuitive as the for loop approach.
6. Use for loop to remove duplicates from a list
primary
Iterate through the input list and store the unique elements in a new list
char_list = ["A", "B", "A", "D", "C", "B", "E"]
final_list = []
for i in char_list:
if i not in final_list:
final_list.append(i)
print(final_list)
# ['A', 'B', 'D', 'C', 'E']
Advanced
In fact, collections are just fine, and you can remove duplicates from a list with one line of code
char_list = ["A", "B", "A", "D", "C", "B", "E"]
set(list(char_list))
# {'A', 'B', 'C', 'D', 'E'}
The two can be converted into each other
char_list = ["A", "B", "A", "D", "C", "B", "E"]
list(set(list(char_list)))
# ['E', 'A', 'B', 'C', 'D']
7. Use for loop to search element in list
primary
Suppose you want to know if an element exists in a list (or set) and return a boolean if it does , True
otherwiseFalse
Basic usage is as follows:
char_list = ["A", "B", "A", "D", "C", "B", "E"]
search_char = "D"
found = False
for i in char_list:
if i == search_char:
found = True
break
print(found)
# True
Too complicated
Advanced
in
This is simplified to a one-line implementation using the keyword
char_list = ["A", "B", "A", "D", "C", "B", "E"]
search_char = "D"
search_char in char_list
# True
8. Use the index variable to iterate over two iterable objects of the same size
primary
Similar to what was mentioned in Section 4, define a variable specially used for indexing, and take values in two lists of the same size, as follows:
list1 = [1, 3, 6, 2, 5]
list2 = [0, 4, 1, 9, 7]
for idx in range(len(list1)):
print("value1 =", list1[idx], "value2 =", list2[idx], sep = " ")
# value1 = 1 value2 = 0
# value1 = 3 value2 = 4
# value1 = 6 value2 = 1
# value1 = 2 value2 = 9
# value1 = 5 value2 = 7
Advanced
A more advanced approach is to use zip()
a function to pair corresponding values in two iterables
list1 = [1, 3, 6, 2, 5]
list2 = [0, 4, 1, 9, 7]
for i, j in zip(list1, list2):
print("value1 =", i, "value2 =", j, sep = " ")
# value1 = 1 value2 = 0
# value1 = 3 value2 = 4
# value1 = 6 value2 = 1
# value1 = 2 value2 = 9
# value1 = 5 value2 = 7
9. Reverse a list using a for loop
primary
Iterate over the list in reverse and add elements to a new list like this:
input_list = [1, 2, 3, 4, 5]
output_list = []
for idx in range(len(input_list), 0, -1):
output_list.append(input_list[idx-1])
print(output_list)
# [5, 4, 3, 2, 1]
Advanced
If you understand slices in Python, then a simple one-liner can be implemented (in fact, built-in methods, etc. can also be implemented)
input_list = [1, 2, 3, 4, 5]
output_list = input_list[::-1]
print(output_list)
# [5, 4, 3, 2, 1]
10. Use a for loop to count the number of occurrences of an element in an iterable object
primary
An easy way to find the frequency of an element is to use a for loop to iterate over the list and count the number of times
char_list = ["A", "B", "A", "D", "C", "B", "E"]
search_char = "B"
char_count = 0
for i in char_list:
if search_char == i:
char_count += 1
print(char_count)
# 2
Advanced
In fact, you can use count()
the method:
char_list = ["A", "B", "A", "D", "C", "B", "E"]
char_list.count("A")
# 2
The same can also be used in strings:
string = "ABADCBE"
string.count("A")
# 2
11. Use for loop to get substring of string
primary
The goal here is to return a n_chars
substring of length , start_index
starting at position .
The way many people solve this problem is to use a for loop, like this:
input_str = "ABCDEFGHIJKL"
start_index = 4
n_chars = 5
output_str = ""
for i in range(n_chars):
output_str += input_str[i+start_index]
print(output_str)
# EFGHI
Advanced
The one-liner is to use slices, which avoids writing a for loop
input_str = "ABCDEFGHIJKL"
start_index = 4
n_chars = 5
output_str = input_str[start_index:start_index+n_chars]
print(output_str)
# EFGHI
12. Define long integer constants
Suppose you want to declare an integer variable with a value of 10²¹
primary
x = 1000000000000000000000
# True
Many times zeros are written consecutively and counted as you type
But if others want to refer to this code, they have to count all the zeros and die on the spot
Advanced
To improve readability, they can be _
separated by (underscore), as follows:
x = 1_000_000_000_000_000_000_000
But it's still a hassle, still counting to zero.
If the number can be represented a^b
in the form, pow()
the method can be used instead:
x = pow(10, 21)
13. Change the case of a string using if condition
Given a string, the goal is to convert uppercase letters to lowercase and vice versa
primary
Check the case of each element, then set specific conditions for each case
input_str = "AbCDeFGhIjkl"
output_str = ""
for i in input_str:
if i.islower():
output_str += i.upper()
elif i.isupper():
output_str += i.lower()
else:
output_str += i
print(output_str)
# aBcdEfgHiJKL
Advanced
swapcase()
method can be used instead .
input_str = "AbCDeFGhIjkl"
output_str = input_str.swapcase()
print(output_str)
# aBcdEfgHiJKL
14. Get the union of two sets
primary
Iterate over the two collections and add elements to a new collection
set_a = {
1, 2, 4, 8}
set_b = {
3, 8, 7, 1, 9}
union_set = set()
for i in set_a:
union_set.add(i)
for i in set_b:
union_set.add(i)
print(union_set)
# {1, 2, 3, 4, 7, 8, 9}
Advanced
Python provides union()
methods for the union of two sets
set_a = {
1, 2, 4, 8}
set_b = {
3, 8, 7, 1, 9}
union_set = set_a.union(set_b)
print(union_set)
# {1, 2, 3, 4, 7, 8, 9}
What's more, it can be extended to any number of input sets:
set_a = {
1, 2, 4, 8}
set_b = {
3, 8, 7, 1, 9}
set_c = {
5, 9, 10, 3, 2}
set_d = {
7, 2, 13, 15, 0}
union_set = set_a.union(set_b, set_c, set_d)
print(union_set)
# {0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 13, 15}
Imagine how many for loops need to be written to merge these four collections. The same collection also has convenient built-in methods such as complement and intersection
15. Change the data type of all elements in the list
Given a list of strings representing integers, the goal is to convert them to a list of integers by changing the data type
primary
Loop through a list and typecast individual elements
input_list = ["7", "2", "13", "15", "0"]
output_list = []
for idx, i in enumerate(input_list):
output_list.append(int(input_list[idx]))
print(output_list)
# [7, 2, 13, 15, 0]
Advanced
Use map()
, like this:
input_list = ["7", "2", "13", "15", "0"]
output_list = list(map(int, input_list))
print(output_list)
# [7, 2, 13, 15, 0]
As its first argument, map()
the method accepts a function int
, and the second argument is an iterable object input_list
.
16. Swap variables
Given two variables, the goal is to pass the value of the first variable to the second variable and the value of the second variable to the first variable
primary
The approach taken by most programmers accustomed to C/C++ is to define a new variabletemp
a = "123"
b = "abc"
temp = a
a = b
b = temp
print(a, b)
# abc 123
Advanced
Python, on the other hand, allows multiple assignments in a single statement, thereby eliminating the need for temporary variables, that is, unpacking, as mentioned in previous tutorials
a = "123"
b = "abc"
a, b = b, a
print(a, b)
# abc 123
17. Generate all combinations of two lists using nested loops
Given two lists ( a
of length n
, b
of length m
), generate all n*m
structures
primary
Write two nested for loops and add all combinations to a list
list1 = ["A", "B", "C"]
list2 = [1, 2]
combinations = []
for i in list1:
for j in list2:
combinations.append([i, j])
print(combinations)
# [['A', 1], ['A', 2], ['B', 1], ['B', 2], ['C', 1], ['C', 2]]
Advanced
Use a method from the itertools library product()
as follows:
from itertools import product
list1 = ["A", "B", "C"]
list2 = [1, 2]
combinations = list(product(list1, list2))
print(combinations)
# [('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]
In fact, including me, I used to use for loops to solve problems many times before. In fact, I am not familiar with built-in functions/methods~
If there are any mistakes in the above content, please point them out. I am a student of everything. See you in the next issue.