【问题标题】:How can i find the median of a number from a list? Python如何从列表中找到数字的中位数? Python
【发布时间】: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


【解决方案1】:

中位数要么是中间元素按值计算,要么是数组长度为偶数时中间两个元素的平均值。

所以首先我们必须对数组进行排序,然后应用我们的逻辑。

def median(l):
    l = sorted(l)
    middle = len(l) // 2
    return l[middle] if len(l) % 2 == 1 else (l[middle - 1] + l[middle]) / 2

请注意,存在 more efficient algorithms 来查找中位数,这需要 O(n) 而不是 O(n log n) 时间,但是它们的实现并非易事,并且在 Python 的标准库中不可用。

【讨论】:

  • 你为什么要做 l[Middle]?那有什么作用?但非常感谢你:D
  • @NeoJoker26 我将middle 计算为中间元素的索引(或者对于偶数长度的数组,在中间之后的索引)。 l[idx] 获取 Python 中索引 idx 处的元素。
【解决方案2】:

这是一个避免使用if/else 分别处理奇数和偶数长度情况的好技巧:中间的索引是(len(nums) - 1) // 2len(nums) // 2。如果长度为奇数,则这些索引相等,因此将这些值相加并除以 2 无效。

请注意,您应该使用// 运算符进行除法,以获得用作索引的整数。

def median(nums):
    nums = sorted(nums)
    middle1 = (len(nums) - 1) // 2
    middle2 = len(nums) // 2
    return (nums[middle1] + nums[middle2]) / 2

例子:

>>> median([1, 2, 3, 4])
2.5
>>> median([1, 2, 3, 4, 5])
3.0

【讨论】:

  • 你能解释一下为什么你写了“def median(nums):”(nums 部分),但是其余的代码看起来确实更有效率,谢谢 :D
  • 这就是在 Python 中定义函数的方式。如果这是一个新概念,请参阅教程:Defining Functions
  • 你能把它编辑到我的代码中吗?我有点理解它,但是当我将它放入我自己的代码中时,我不断收到错误消息。我做了这个 def Median(MedianList): MedianList = [2,4,6] print("你想把什么数加到数组中,输入 0 取平均值") try: Int = int(input()) if Int == 0: QuitApp() else: MedianList.append(Int) except: print("请输入一个数字") middle1 = (len(MedianList) - 1) // 2 middle2 = len(MedianList) // 2返回 (MedianList[middle1] + MedianList[middle2]) / 2
  • 不,我不能为你编写代码,尤其是因为这是你的作业。 Stack Overflow 是一个问答网站,而不是代码编写服务。
【解决方案3】:

正如其他人所提到的,我会使用sorted(MedianT) 而不是MeadianT.sort()

此外,使用基于数组的索引而不是 .index() 函数。
例如,这个:

print(MedianList[MedianT])

而不是这个:

print(MedianList.index(MedianT))

我在下面的 cmets 中包含了在 Python 中查找数组中值的逻辑和思维过程。

def median(array):
    length = len(array)
    sorted_arr = sorted(array) # sorting in O(n) time or linear complexity
    # we are subtracting 1 from overall 
    # length because indexing is 0-based
    # essentially indexes of arrays start at 0
    # while counting length starts at 1
    # idx_norm = (length-1) / 2 # using only single division operator yields a float
    idx = (length-1) // 2 # using floor division operator // yields an Int which can be used for index

    # we run a simple condition to see 
    # whether if the overall length of array
    # is even or odd.
    # If odd then we can use index value (idx) to find median
    # we use modulus operator to see if if there is any remainder
    # for a division operation by 2. If remainder equals 0 then
    # array is even. If not array is odd.
    if length % 2 == 0:
        return (sorted_arr[idx] + sorted_arr[idx + 1]) / 2.0 # if you need an Int returned, then wrap this operation in int() conversion method
    else:
        return sorted_arr[idx]
    # If even we have to use index value (idx) and the next index value (idx + 1)
    # to create total and then divide for average

a = [1, 2, 3, 4, 12, 1, 9] # 7 elements, odd length --> return 3
b = [2, 3, 7, 6, 8, 9] # 6 elements, even length --> return 6.5

median(a)
median(b)

如果您有任何问题,请告诉我,希望对您有所帮助。干杯!

【讨论】:

  • 这是一个很好的解释,我明白了:D 谢谢
猜你喜欢
  • 1970-01-01
  • 2016-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 2014-07-28
  • 2019-11-06
  • 2012-09-09
相关资源
最近更新 更多