除了不传递值并尝试调用dict之外,您正在计算列表完全填充之前的平均值,在代码中,当您完成附加后,在循环外计算平均值:def posNumAvg(values):
pos = []
# average = 0 don't need to declare variable
for i in values:
if i > 0:
pos.append(i)
average = sum(pos)/len(pos) # only calculate once when done
return average
在allNumAvg中,您已经有了一个值列表,然后再创建一个完全相同的值的列表,只需使用值本身:
^{pr2}$
也可以使用列表理解:def num_list():
# "-9999" is the sentinel value which will break the loop if entered
values = [int(i) for i in iter(lambda:input("Enter any amount of numbers or -9999 to quit: "),"-9999")]
return values
def all_num_avg(values):
average = sum(values) / len(values)
return average
def pos_num_avg(values):
pos = [x for x in values if x > 0]
return sum(pos) / len(pos)
def non_pos_avg(values):
non = [i for i in values if i < 1]
return sum(non) / len(non)
values = num_list()
def store():
return {'all': all_num_avg(values), 'pos': pos_num_avg(values), 'def': non_pos_avg(values)}
我还使用下划线更改了函数名,它与pep-8 style guide一致
理想情况下,在获取用户输入时,最好使用try/except来捕获来自用户的错误输入:def num_list():
values = []
while True:
try:
inp = int(input("Enter any amount of numbers or -9999 to quit: "))
if inp == -9999:
return values
values.append(int(inp)) # any input that cannot be cast will raise a ValueError which we catch and then inform the user
except ValueError:
print("Invalid input")
return values
如果用户没有输入正数或负数,那么您还将得到一个zeroDivisionError,因此您还需要通过再次使用try/except或返回默认值(如果列表为空)来处理这种情况,我们可以使用默认值,因为我们已经验证了输入以确保是一个数字:def non_pos_avg(values):
non = [i for i in values if i < 1]
return sum(non) / len(non) if non else 0
所有这些都可以在一个函数中完成,在末尾更新dict并返回它:def store():
store_dict = {}
values = []
while True:
try:
inp = int(input("Enter any amount of numbers or -9999 to quit: "))
if inp == -9999:
break
values.append(int(inp))
except ValueError:
print("Invalid input")
pos = [x for x in values if x > 0]
non = [i for i in values if i < 1]
# catch cases where user does not enter a mixture of pos and negative nums of break on the first iteration
# if values etc.. will all evaluate to False for an empty list
store_dict["all"] = sum(values) / len(values) if values else 0
store_dict["pos"] = sum(pos) / len(pos) if pos else 0
store_dict["def"] = sum(non) / len(non) if non else 0
return store_dict
print(store())
因为您使用的是python3.4,所以我们也可以让statistics module来处理平均值:from statistics import mean
def store():
store_dict = {}
values = []
while True:
try:
inp = int(input("Enter any amount of numbers or -9999 to quit: "))
if inp == -9999:
break
values.append(int(inp))
except ValueError:
print("Invalid input")
pos = [x for x in values if x > 0]
non = [i for i in values if i < 1]
store_dict["all"] = mean(values) if values else 0
store_dict["pos"] = mean(pos) if pos else 0
store_dict["def"] = mean(non) if non else 0
return store_dict
根据您的评论,如果您想返回dict和列表,您可以同时返回并解压缩:def store():
store_dict = {}
values = []
while True:
try:
inp = int(input("Enter any amount of numbers or -9999 to quit: "))
if inp == -9999:
break
values.append(int(inp))
except ValueError:
print("Invalid input")
pos = [x for x in values if x > 0]
non = [i for i in values if i < 1]
store_dict["all"] = mean(values) if values else 0
store_dict["pos"] = mean(pos) if pos else 0
store_dict["def"] = mean(non) if non else 0
return store_dict,values
d, vals = store() # unpack
print(d, vals)