01
introduction
In the programming world, everyone hopes that they can write the best code in the world. In fact, the best code often needs to have the best code quality. Diligence can make up for clumsiness, and being good at summarizing can often quickly improve everyone's programming skills. This article focuses on briefly explaining four Python skills that are not often used in daily life, hoping to improve your work efficiency when coding.
Without further ado, let's get started!
02
Get the n largest numbers
max([15, 21, 30, 20])
# ouput: 30
But what if we extend it to get a list of the n largest numbers? Students who have studied data structure may be able to think of building a big top heap data structure. Well, there is a module called heapq in Python, which can implement the above functions very conveniently. As follows:
import heapq
heap = [10, 5, 18, 1, 100]
# heapq.nlargest(n, iterable)
n_largest_numbers = heapq.nlargest(3, heap)
# show result
print(n_largest_numbers)
The resulting output is as follows:
[100, 18, 10]
03
Get the n smallest numbers
As we know about the max function, we can know what the min function does:
min([15, 21, 30, 20])
# ouput: 15
import heapq
heap = [10, 5, 18, 1, 100, 8, 7]
# heapq.nsmallest(n, iterable)
n_smallest_numbers = heapq.nsmallest(4, heap)
# show result
print(n_smallest_numbers)
[1, 5, 7, 8]
04
delete a specific part of a string
Suppose we have the string +-+-+Python . If we only need to get the part of the above string, that is Python , we can use the removeprefix function in the python string module. The example is as follows:
myString = "+-+-+Python"
new_string = myString.removeprefix("+-+-+")
# show result
print(new_string)
The resulting output is as follows:
Python
05
Remove duplicate elements from a list
In order to remove duplicate elements from a list, maybe we know that we can transform through sets, as follows:
li = [10, 15, 10, 10, 5, 5]
without_duplicates = list(set(li))
print(without_duplicates)
The output is as follows:
[10, 5, 15]
But the above implementation is not a very professional implementation, because the output results are not output in the original order, so let me show you the second way:
li = [10, 15, 10, 10, 5, 5]
without_duplicates = dict.fromkeys(li)
print(list(without_duplicates))
The output is as follows:
[10, 15, 5]
06
Summarize
Are you out of school?
Click the small card above to follow me
Thousands of waters and thousands of mountains always care about love, just click to see if it works.