Python 如何计算数字列表中的平均数
除了最后几行之外,所有的东西都在工作,在那里我得到了一个打字错误。不确定哪些数据类型需要更改。有什么想法吗?该程序只需掷两个骰子,并计算100个骰子的平均数Python 如何计算数字列表中的平均数,python,list,sum,Python,List,Sum,除了最后几行之外,所有的东西都在工作,在那里我得到了一个打字错误。不确定哪些数据类型需要更改。有什么想法吗?该程序只需掷两个骰子,并计算100个骰子的平均数 #two dice roll with average of rolls import random total=[] def roll(): for i in range(100): roll_d=random.randint(1,6), random.randint(1,6) total.a
#two dice roll with average of rolls
import random
total=[]
def roll():
for i in range(100):
roll_d=random.randint(1,6), random.randint(1,6)
total.append(roll_d)
print(roll_d)
def main():
roll()
s=sum(total)
average=s/100.0
print(average)
main()
total中的每个元素都是两个整数的元组 您必须定义这些元组的求和方式。也许您想单独添加卷:
def roll():
for i in range(100):
roll_d=random.randint(1,6), random.randint(1,6)
total.extend(roll_d)
print(roll_d)
此处total.extend()
将两个卷分别传递到total
列表。或者您可能需要存储卷的总和:
def roll():
for i in range(100):
roll_d=random.randint(1,6), random.randint(1,6)
total.append(roll_d[0] + roll_d[1])
print(roll_d)
如果您确实希望将卷成对存储,则需要调整sum()
调用以将各个卷号相加:
s = sum(r for pair in total for r in pair)
正如马丁指出的,total的元素是元组——每个骰子卷(例如,
(3,4)
,(1,1)
,等等)
所以,如果我正确理解了你的意图,你也需要把它们加在一起。不能直接对元组求和
以下内容将在求和之前将各卷相加:
s=sum(map(λx:x[0]+x[1],总计))
请不要硬编码
100.0
。建议使用s*1.0/len(total)
数组而不是列表:
import numpy as np
total = np.random.randint( low=1, high=6+1, size=(100,2) ) # 100 by 2 array
total.mean( ) # average of all values ( 1 number)
total.mean( axis=0 ) # average of each column ( 2 numbers)
total.mean( axis=1 ) # average of each row ( 100 numbers)
有很多方法:
print reduce(lambda x, y: x + y, total)/(len(total)*1.0)
或
1.0是为了确保得到浮点除法
或者使用numpy:
import numpy as np
print np.mean(total)
您好,您应该准确地发布您的错误:它在什么指令上失败?
import numpy as np
print np.mean(total)