【问题标题】:How to print mean , median and mode in python 3如何在 python 3 中打印均值、中位数和众数
【发布时间】:2017-12-16 23:13:32
【问题描述】:

我是 python 编程的新手,我的代码出现运行时错误。任何帮助表示赞赏。

import statistics

tc = int(input())

while tc > 0:
    n = int(input())
    arr = input()
    l = list(map(int, arr.split(' ')))
    print("{} {} {}".format(statistics.mean(l), statistics.median(l), statistics.mode(l)))
    tc = tc - 1

错误

StatisticsError: no unique mode; found 2 equally common values

输入格式

第一行由一个整数 T 组成,表示测试用例的数量。 每个测试用例的第一行由一个整数 N 组成,表示数组的大小。 以下行由 N 个空格分隔的整数 Ai 组成,表示数组中的元素。

输出格式

对于每个测试用例,输出一行包含三个分隔的整数,表示数组的均值、中位数和众数

示例输入

1
5
1 1 2 3 3

样本输出

2 2 1

【问题讨论】:

  • 能否将错误输出添加到您的问题中?
  • StatisticsError: no unique mode; found 2 equally common values
  • @cᴏʟᴅsᴘᴇᴇᴅ 谢谢。我将错误编辑到问题中。
  • 这不是错误,而是statistics.mode 函数的未来
  • @flevinkelming,我提到过,我收到运行时错误 (ideone.com/QAubql)

标签: python arrays python-3.x statistics


【解决方案1】:

您可以添加一个由try...except 包围的变量mode,如果statistics 有错误,则获取模式different way

try:
  mode=statistics.mode(l)
except:
  mode=max(set(l),key=l.count)
print("{} {} {}".format(statistics.mean(l), statistics.median(l), mode))

【讨论】:

  • @KartikMadaan ....你把 try...except 在while 循环中,l 没有在循环之外定义,否则
【解决方案2】:

你好 Kartik Madaan,

试试这个代码,

使用 Python 3.X

import statistics
from statistics import mean,median,mode

tc = int(input())

while tc > 0:
    n = int(input())
    arr = input()
    l = list(map(int,arr.split()))
    mod = max(set(l), key=l.count)
    print(int(mean(l)),int(median(l)),mod)
    tc = tc - 1

希望我的回答对你有帮助。
如有任何疑问,请发表评论。

【讨论】:

  • 你好kartik你说什么我不明白?
  • 您的代码出现编译错误:上述链接中的错误已删除
  • 等一分钟?
  • 您在 ==>ideone 中使用了错误的代码。请运行我上面的代码。
  • Invalid syntax of Print 语句给出错误,而不是 raw_input() ,你应该使用 input()
猜你喜欢
  • 2019-03-07
  • 2021-11-10
  • 1970-01-01
  • 2021-04-14
  • 1970-01-01
  • 1970-01-01
  • 2017-01-11
  • 1970-01-01
  • 2021-05-12
相关资源
最近更新 更多