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
尝试使用
try
语句希望能有所帮助
Python已经内置了
min
和max
函数来查找列表中的最小值和最大值您可以使用统计数据包中的^{} 而不是
mode()
。当有多个模式可供选择时,这将返回多个值。您可以从中获取min()
:[注意:这需要python 3.8]
相关问题 更多 >
编程相关推荐