Python – 列表的多模式
有时,在使用Python列表时,我们可能会遇到需要在列表中查找模式的问题,即最常出现的字符。但有时,我们可以有超过 1 种模式。这种情况称为多模。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环+公式
解决这个问题的更简单的方法是使用公式来查找多模并使用循环简写来执行。这是解决这个问题的最基本的方法。
# Python3 code to demonstrate working of
# Multimode of List
# using loop + formula
import math
from collections import Counter
# initialize list
test_list = [1, 2, 1, 2, 3, 4, 3]
# printing original list
print("The original list is : " + str(test_list))
# Multimode of List
# using loop + formula
res = []
test_list1 = Counter(test_list)
temp = test_list1.most_common(1)[0][1]
for ele in test_list:
if test_list.count(ele) == temp:
res.append(ele)
res = list(set(res))
# printing result
print("The multimode of list is : " + str(res))
输出 :
The original list is : [1, 2, 1, 2, 3, 4, 3]
The multimode of list is : [1, 2, 3]
方法 #2:使用statistics.multimode()
也可以使用 mulimode() 的内置函数来执行此任务。这是Python版本 >= 3.8 中的新功能。
# Python3 code to demonstrate working of
# Multimode of List
# using statistics.multimode()
import statistics
# initialize list
test_list = [1, 2, 1, 2, 3, 4, 3]
# printing original list
print("The original list is : " + str(test_list))
# Multimode of List
# using statistics.multimode()
res = statistics.multimode(test_list)
# printing result
print("The multimode of list is : " + str(res))
输出 :
The original list is : [1, 2, 1, 2, 3, 4, 3]
The multimode of list is : [1, 2, 3]