gpt4 book ai didi

python - 如何使用 Python 中的函数返回列表算术运算的结果

转载 作者:太空宇宙 更新时间:2023-11-03 21:23:52 25 4
gpt4 key购买 nike

我正在尝试计算整数列表的平均值、中位数和众数。但是,我收到的错误(根据我的理解)表明我无法返回浮点答案。我不明白为什么列表会出现这种情况。我所做的只是对平均值和中位数进行基本算术运算(使用众数统计框架)。输出应该只有 1 个答案。

这是我的代码:

from statistics import mode

listOfNumbers = [1, 2, 6, 7, 8, 9, 3, 4, 5, 10, 10]
listOfNumbers.sort()
length = len(listOfNumbers)

def median(numbers):
if((len(list)) % 2 == 0):
median = (listOfNumbers[(length)/2] + listOfNumbers[(length)/2-1]) / 2
else:
median = listOfNumbers[(length-1)/2]
return

def meanMedianMode(numbers):
# TODO your code here!
meanOfNumbers = (sum(numbers))/(len(numbers))
medianOfNumbers = median(numbers)
modeOfNumbers = mode(numbers)
print("The mean of the numbers is: " + str(meanOfNumbers))
print("The median of the numbers is: " + str(medianOfNumbers))
print("The mode of the numbers is: " + str(modeOfNumbers))

meanMedianMode(listOfNumbers)

这是我的输出:

TypeError                                 Traceback (most recent call last)
<ipython-input-27-03d94981e27d> in <module>()
21 print("The mode of the numbers is: " + str(modeOfNumbers))
22
---> 23 meanMedianMode(listOfNumbers)
24

<ipython-input-27-03d94981e27d> in meanMedianMode(numbers)
15 # TODO your code here!
16 meanOfNumbers = (sum(numbers))/(len(numbers))
---> 17 medianOfNumbers = median(numbers)
18 modeOfNumbers = mode(numbers)
19 print("The mean of the numbers is: " + str(meanOfNumbers))

<ipython-input-27-03d94981e27d> in median(numbers)
9 median = (listOfNumbers[(length)/2] + listOfNumbers[(length)/2-1]) / 2
10 else:
---> 11 median = listOfNumbers[(length-1)/2]
12 return
13

TypeError: list indices must be integers or slices, not float

最佳答案

问题出在这一行:

median = listOfNumbers[(length-1)/2]

在 python 3 中,(length-1)/2 是一个 float,而不是 int,因此错误 list索引必须是整数或切片,而不是 float

最简单的解决方法是将结果转换回 int:

...
median = listOfNumbers[int((length - 1) / 2)]
...

事实上,我会像这样重构整个 median() 函数,因为您混合了本地变量和全局变量,并且不返回任何内容:

def median(numbers):
length = len(numbers)
if length % 2 == 0:
return (listOfNumbers[int(length / 2)] + listOfNumbers[int(length / 2) - 1]) / 2
else:
return listOfNumbers[int((length - 1) / 2)]

关于python - 如何使用 Python 中的函数返回列表算术运算的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54000464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com