列表中所有值的平均值有没有更“Pythonic”的方法?

2024-10-01 17:40:06 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我遵循Python初学者指南,并进行了以下练习:

Create a list containing 100 random integers between 0 and 1000 (use iteration, append, and the random module). Write a function called average that will take the list as a parameter and return the 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)

提前谢谢!在


Tags: andthe列表forreturndefrandomlist
2条回答

使用Python的内置sumlen函数:

print(sum(myList)/len(myList))

我同意上面关于使用sum的建议。在

虽然我不喜欢使用列表理解来运行固定数量的迭代,但是您的createRandList函数体可以是:

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

(另外,我发现randint更具可读性,因为“stop”值是您想要的值,而不是您想要的值+1。)在

在任何情况下,您可以省去在数字上调用int()的行,randrange的输出已经是int

相关问题 更多 >

    热门问题