簡體   English   中英

如何從列表中找到數字的中位數? Python

[英]How can i find the median of a number from a list? Python

我正在嘗試在列表中找到中位數。 找到中位數的方程是 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

我該怎么做才能得到中位數? 我知道已經存在這樣的問題,但我想嘗試不同的方式。

這是避免使用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

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

此外,使用基於數組的索引而不是.index()函數。
例如,這個:

print(MedianList[MedianT])

而不是這個:

print(MedianList.index(MedianT))

我在下面的注釋中包含了在 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)

如果您有任何問題,請告訴我,希望對您有所幫助。 干杯!

中位數是value的中間元素,或者如果數組的長度為偶數,則為中間兩個元素的平均值。

所以首先我們必須對數組進行排序,然后應用我們的邏輯。

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

請注意,存在更有效的算法來找到中位數,這需要O(n)而不是O(n log n)時間,但是它們實現起來並不簡單,並且在 Python 的標准庫中不可用。

我創建了一個類。 您可以使用 addNum 方法將元素添加到列表中。 findMedian 方法將檢查列表的長度是奇數還是偶數,並根據情況為您提供中位數。

class MedianFinder:
    def __init__(self):
        num_list = []
        self.num_list = num_list

    def addNum(self, num):
        self.num_list.append(num)
        return self.num_list

    def findMedian(self):
        # Check len of list
        if len(self.num_list) % 2 == 0:
            l = int(len(self.num_list) / 2)
            return (self.num_list[l - 1] + self.num_list[l]) / 2

        else:
            l = math.floor(len(li) / 2)
            return self.num_list[l]

示例用法;

s.addNum(2)
s.addNum(4)
s.addNum(6)
s.addNum(8)
print(s.findMedian())

輸出:5.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM