2014-01-30 77 views
2

所以我下面的一個初學者指南Python和我得到這個練習:列表中所有值的平均值 - 是否有更多的「Pythonic」方法來執行此操作?

創建一個包含0到1000之間的100個隨機整數(使用 迭代,追加和隨機模塊)的列表。編寫一個名爲 average的函數,它將列表作爲參數並返回平均值。

我在幾分鐘內輕鬆地解決了這個問題,但chapter也提到了幾種方法,通過列表來遍歷和分配多個值列表,並說我不知道​​我是否完全聽懂了沒有變數,所以我不知道知道是否可以用較少的線條做到這一點。這是我的回答:

import random 

def createRandList(): 
    newlist = [] 
    for i in range(100): 
     newint = random.randrange(0,1001) 
     newlist.append(newint) 
    return newlist 

def average(aList): 
    totalitems = 0 
    totalvalue = 0 
    for item in aList: 
     intitem = int(item) 
     totalitems = totalitems + 1 
     totalvalue = totalvalue + intitem 
    averagevalue = totalvalue/totalitems 
    return averagevalue 

myList = createRandList() 
listAverage = average(myList) 

print(myList) 
print(listAverage) 

在此先感謝!

回答

9

使用Python的內建sumlen功能:

print(sum(myList)/len(myList)) 
+3

而createRandList可能[在範圍random.randrange(0,1001),其中i(100)]被表達爲'''''' – nathancahill

+0

感謝!很高興找出'sum'在列表上工作。 – reggaelizard

+3

另外,Python變量通常是lower_case_with_underscores而不是mixedCase。 my_list而不是myList。 – nathancahill

1

我的建議,同意上述關於使用sum

雖然我不喜歡使用列表理解只是運行的迭代固定數量的,你createRandList函數體可能是簡單的:

return [random.randint(0,1000) for i in range(100)] 

(另外,我發現randint有點更具可讀性,因爲「停止」值是你想要的值,而不是你想要的值+1。)

在任何情況下,你可以免去你的電話號碼int() - randrange的輸出已經是int。

+0

雖然'randint'呼籲更普遍常識,'randrange'優選由於其與Python約定,例如稠度範圍(start,stop)'和片語法('[start,stop]')。實際上,在Python歷史中,randint已被多次棄用。請參閱http://stackoverflow.com/a/2568917/2980246 – jayelm

相關問題