How does Python take the number of different characteristics from the list

Sometimes, we need to take some numbers with specific characteristics from a list of numbers. For example: the largest number, the smallest number, the number with the most occurrences, the median, and so on. At this time, we need to use some specific functions to achieve our purpose.

1. Find the maximum, minimum, and average of a list of numbers

lst = [1, 3, 3, 4, 5]
max_num = max(lst)
min_mim = min(lst)

If you want to use the built-in function of statistics to find the average

from statistics import *
lst = [1, 3, 3, 4, 5]
print(average(lst)) 

2. Find the number with the most occurrences in the list of numbers

Many numbers are repeated in the list of numbers, how to find which of these numbers appears the most times? Two methods are described below

The first method: use set to deduplicate, use max to obtain the maximum value, and the key value to obtain the number of elements. The code is as follows:

lst = [1, 3, 3, 4, 5]
print(max(set(ls),key=ls.count))

The second: use the mode in statistics

from statistics import *
lst = [1, 3, 3, 4, 5]
print(mode(lst))

3. Find the largest or smallest three numbers in the list

At this time we need to use a heapq module. The heapq module in Python is primarily used to implement priority queues, but can also be used to sort lists of numeric data. heap is a very efficient and interesting data structure, often used in sorting, finding the smallest/largest N numbers and other scenarios. See my previous article for details:

The code sample is as follows:

import heapq
lst = [1, 3, 3, 4, 5]
largest = heapq.nlargest(3, lst) # 求列表中最大的三个数
smallest = heapq.nsmallest(3, lst) # 求列表中最小的三个数
print(largest)

4. Find the median in the list

Still using the built-in statistics module of Python, this time using the median, the median is also divided into two situations: median_low and median_high.

from statistics import * 
lst = [1, 3, 3, 4, 5] 
print(median(lst)) # 样本偶数个时,取中间两个数的平均数
print(median_low(lst)) # 样本偶数个时,取中间两个较小的那个数
print(median_high(lst)) # 样本偶数个时,取中间两个较大的那个数

5. Reflection after school

  1. Today, after reading the Python tutorial by Mr. Dong Fuguo, I learned about the usage of statistics. Then I summarized the previous development, and finally wrote the article about taking numbers from this list in more detail.
  2. A lot of information on the Internet is relatively scattered, and more knowledge must be obtained from books. Now I decide to read more books recommended to me by Zhihu, as well as sample books from publishers, etc.

Guess you like

Origin blog.csdn.net/henanlion/article/details/131116717