当模式不可用时,如何打印列表中的最小数字?

2024-04-27 01:04:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python数组或列表中找到模式,但如果所有数字只出现一次(或者我们可以说没有模式),我想打印最小的数字

n_num = [64630, 11735, 14216, 99233, 14470, 4978, 73429, 38120, 51135, 67060]

from statistics import mode


def mode(n_num):
            n_num.sort()
            m = min(n_num)
            return m
print(str(mode(n_num)))

Tags: fromimport列表returnmodedef模式数字
3条回答

尝试使用try语句

import statistics

def special_mode(iterable):
    try:
        result = statistics.mode(iterable)
    except statistics.StatisticsError: # if mode() fail, it do min()
        result = min(iterable)
    return result

mylist = [0, 1, 6, 9, 1, -7]
print(special_mode(mylist))
# return the 1 because of the mode function

mylist = [0, 1, 6, 9, -7]
print(special_mode(mylist))
# return the -7 beacuse it's the smallest

希望能有所帮助

Python已经内置了minmax函数来查找列表中的最小值和最大值

n = [64630, 11735, 14216, 99233, 14470, 4978, 73429, 38120, 51135, 67060]

smallest_number = min(n)
largest_number = max(n)

您可以使用统计数据包中的^{}而不是mode()。当有多个模式可供选择时,这将返回多个值。您可以从中获取min()

from statistics import multimode


n_num = [10, 9, 1, 2, 3, 4]
min(multimode(n_num))
# 1

n_num = [10, 9, 1, 2, 3, 4, 9, 10 ]
min(multimode(n_num))
#9

[注意:这需要python 3.8]

相关问题 更多 >