所以我下面的一個初學者指南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)
在此先感謝!
而createRandList可能[在範圍random.randrange(0,1001),其中i(100)]被表達爲'''''' – nathancahill
感謝!很高興找出'sum'在列表上工作。 – reggaelizard
另外,Python變量通常是lower_case_with_underscores而不是mixedCase。 my_list而不是myList。 – nathancahill