【问题标题】:Finding mode and median of a file with Python使用 Python 查找文件的模式和中位数
【发布时间】:2015-03-22 02:15:55
【问题描述】:

我在一个项目中的这部分代码遇到问题,并尝试以多种方式执行众数和中位数,但均未成功。但是,我确实需要在模式部分使用字典,所以那里的任何建议都会非常有帮助。

    # Find median
    order = converted_numbers.sort()
    middle = count/2
    if middle % 2 == 0:
        median = (converted_numbers[middle - 1] + converted_numbers[middle]) / 2
    else:
        median = converted_numbers[middle]

    # Mode calculations
    number_counts = {}
    mode = 0
    freq = 0
    for i in converted_numbers:
        if i in number_counts:
            number_counts[i] += 1
        else:
            number_counts[i] = 1
    for i in number_counts:
        counts = int(number_counts[i])
        mode = max(counts)

【问题讨论】:

  • 你用的是哪个版本的python? 2个还是3个?
  • 我使用的是版本 3,如果您需要查看我的其余代码,我很乐意提供

标签: python list dictionary mode median


【解决方案1】:

您的代码有一些问题:

  • list.sort() 不返回值。因此,如果您想要一个排序列表(与原始列表分开)。

    ordered_numbers = converted_numbers[:] # copy it
    ordered_numbers.sort()
    
  • 使用楼层划分,并检查count是否是偶数,而不是middle

    middle = count // 2
    if count % 2 == 0:
        median = (ordered_numbers[middle - 1] + converted_numbers[middle]) / 2
    else:
        median = ordered_numbers[middle]
    
  • 要计算模式,您可以使用 python 的核心库之一,collections 库,然后快速获取它:

    from collections import Counter
    
    counter = Counter(ordered_numbers) # no need to be sorted
    mode    = counter.most_common(1)   # returns the most commonly occuring item
    

编辑:

既然要求是使用字典,我们可以简单的写成这样:

number_counts = {}
for num in ordered_numbers:
    if number_counts.get(num, None):
        number_counts[num] = 1
    else:
        number_counts[num] += 1

mode = ordered_numbers[0] # set to a number already in list
mode_freq = 0
for num, freq in number_counts.items():
    if freq > mode_freq:
        mode, mode_freq = num, freq

您可以使用defaultdict 代替常规的dict,这样您就可以在元素存在时不需要

from collections import defaultdict

number_counts = defaultdict(int)
for num in ordered_numbers:
    number_counts[num] += 1

mode = #.... same as above

【讨论】:

  • 非常感谢!但是对于这种模式,我确实必须使用字典,这是我试图做的,想知道你是否有任何建议来专门这样做?
  • 具体来说,我在第 56 行不断收到此错误消息,在 mode = max(counts) TypeError: 'int' object is not iterable
猜你喜欢
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 2018-06-24
  • 2021-04-14
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多