简体   繁体   English

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

[英]How to print smallest number from list when mode is not available?

I Would like to find Mode in python array or list, but if all numbers appears at only once(or we can say there is no Mode) I wanted to print smallest number.我想在 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)))

You can use multimode() from the statistics package instead of mode() .您可以使用统计 package 中的multimode()而不是mode() This will return multiple values when there is more than one mode to choose from.当有多个模式可供选择时,这将返回多个值。 You can take the min() from that:您可以从中获取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

[Note: this requires python 3.8] [注意:这需要 python 3.8]

try to use the try statement尝试使用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

hope it was helpful希望对您有所帮助

Python already has a min and max function built-in to find the smallest and largest values in a list Python 已经内置了一个minmax function 以查找列表中的最小值和最大值

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM