這裏是我的模塊的一部分:gm.py進口煩惱
def avg_list(list):
sum = 0
for num in list:
sum += num
avg = float(sum)/len(list)
print avg
def median(list):
i = len(list)
if not i%2: # if i divided my 2 has no remainder
return (list[(i/2)-1]+list[i/2])/2.0 # return the value of this block
else:
median = sorted(list)[len(list)/2] # otherwise, when the list is sorted, the index of len(s)/2 is the middle number.
return median
當我保存這個爲「gm.py」,並打開一個新的腳本頁面輸入以下功能:
import gm
def stats(list):
stats = {} # empty dict named stats
stats['average'] = avg_list(list) # Stats(key)[average] = mean of the list of numbers [values]
stats['median'] = median(list) # same for median
return stats
當我運行這個程序並鍵入stats([2,3,4,5,6])...我得到一個錯誤,說全局變量avg_list沒有定義。我不確定我是否正確地進行導入? 我是否需要從gm import avg_list()中執行類似操作?
如果我添加排序到第一個分支,我收到一個TypeError:'int'對象不可迭代。 –
@ G.G你不能把整個東西都包裝在'sorted'中,我的意思是你需要對列表進行排序_before_查找中位數,列表中是否有奇數或偶數條目。嘗試在函數的頂部添加'list = sorted(list)'或'list.sort()',並去掉其他調用'sorted'。 – agf
@afg啊,我的錯......我可以那樣做。我用適當的進口再次運行程序,並回來了: >>> stats([2,5,6,7,8]) 5.6 {'average':None,'median':6} –