7

我正在创建一个程序来查找平均值、中位数、众数或范围。当我运行它时,它工作正常,直到它进入计算答案的部分。它给了我一个“不能使用灵活类型减少预制件”的错误。我已经搜索了这个错误,但找不到我需要修复的内容。这是我第一次使用 numpy,所以任何帮助都会很棒。

import sys
import numpy as np

welcomeString = input("Welcome to MMMR Calculator\nWhat would you like to calculate(Mean,Median,Mode,Range):")

if welcomeString.lower() == "mean":
   meanNumbers = input("What numbers would you like to use?:")
   print (np.average(meanNumbers))
   stop = input()

if welcomeString.lower() == "median":
    medianNumbers = input("What numbers would like to use?:")
    print (np.median(medianNumbers))
    stop = input()

if welcomeString.lower() == "mode":
    modeNumbers = input("What numbers would you like to use?:")
    print (np.mode(modeNumbers))
    stop = input()

if welcomeString.lower() == "range":
    rangeNumbers = input("What numbers would you like to use?:")
    print (np.arange(rangeNumbers))
    stop = input()
4

2 回答 2

7

您正在将字符串传递给不允许的函数。

>>> meanNumbers = input("What numbers would you like to use?:")
What numbers would you like to use?:1 2 3 4 5 6
>>> np.average(meanNumbers)
    #...
TypeError: cannot perform reduce with flexible type

您需要从中创建一个数组或列表。

>>> np.average(list(map(float, meanNumbers.split())))
3.5

如果您用逗号分隔元素,请按逗号分隔。

>>> np.average(list(map(float, meanNumbers.split(','))))
    3.5
于 2013-07-25T18:04:05.670 回答
6

这不是答案(请参阅@Sukrit Kalra 对此的回复),但我看到了一个机会来演示如何编写我无法放弃的更简洁的代码。您有大量的代码重复,这将导致将来难以维护代码。试试这个:

import sys
import numpy as np

welcomeString = input("Welcome to MMMR Calculator\nWhat would you like to calculate(Mean,Median,Mode,Range):")
welcomeString = welcomeString.lower() # Lower once and for all

# All averages need to do this
numbers = input("What numbers would you like to use?:")
numbers = list(map(float, numbers.split(','))) # As per Sukrit Kalra's answer

# Use a map to get the function you need
average_function = { "mean": np.average,
                     "median": np.median,
                     "mode": np.mode,
                     "range": np.arange,
                   } 

# Print the result of the function by passing in the
# pre-formatted numbers from input
try:
    print (average_function[welcomeString](numbers))
except KeyError:
    sys.exit("You entered an invalid average type!")

input() # Remove when you are done with development
于 2013-07-25T18:27:02.133 回答