我正在创建一个程序来查找Mean,Median,Mode或Range。当我运行它时它工作正常,直到它到达计算答案的部分。它给了我一个“无法预先形成减少灵活类型”的错误。我搜索了这个错误但找不到我需要解决的问题。这是我第一次使用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()
答案 0 :(得分:6)
您正在将字符串传递给不允许的函数。
>>> 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
答案 1 :(得分: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