【发布时间】:2020-06-06 03:52:34
【问题描述】:
我正在尝试在列表中查找中位数。找到中位数的方程是 N 项/2。我尝试的代码是查找并索引该数字,但是当我索引时我得到 0 或错误,这是为什么呢?
def Median():
#MedianList_Str = ""
MedianList = [2,4,6]
print("What number do you want to add to the array, enter 0 to exit")
try:
Int = int(input())
if Int == 0:
QuitApp()
else:
MedianList.append(Int)
except:
print("Please enter a number")
MedianT = math.floor(len(MedianList)/2) #finds the nth term
MedianList.sort #sorts the list so you can find the median term
MedianList_Str.join(MedianList)
这就是我所做的。我也试过索引
def Median():
MedianList_Str = ""
MedianList = [2,4,6]
print("What number do you want to add to the array, enter 0 to exit")
try:
Int = int(input())
if Int == 0:
QuitApp()
else:
MedianList.append(Int)
except:
print("Please enter a number")
MedianT = math.floor(len(MedianList)/2) #finds the nth term
MedianList.sort #sorts the list so you can find the median term
print(MedianList.index(MedianT))
这让我 0
我该怎么做才能得到中位数?我知道已经存在这样的问题,但我想尝试不同的方式。
【问题讨论】:
-
你从来没有调用过
sort,(sort()),你也从来没有调用过你的Median函数。 -
你必须调用排序函数(
MedianList.sort())。此外,您希望运行MedianList[MedianT]而不是.index,因为.index查找 一个值,而[]访问 一个值。 -
这能回答你的问题吗? Finding median of list in Python
-
@wjandrea:如果只是“如何获得它?”那么是的。但我怀疑他们正在尝试自己编写,并且想知道它为什么会损坏(rassar 在上面的评论中解释了)。
-
@rassar:代码很明显没有重新分配
MedianList;如果是这样,你会得到一个完全不同的错误。你不能说MedianList = MedianList.sort()而不破坏所有内容,当他们显然没有这样做时提出它很奇怪。
标签: python python-3.x