【问题标题】:Taking out only integers to sum and create an average python只取出整数求和并创建一个平均python
【发布时间】:2013-06-04 02:32:51
【问题描述】:

您好,我打印时的函数输出是

average = ['2.06556473829 is the average for a', 
           '1.48154269972 is the average for b', 
           '1.56749311295 is the average for c',
           '2.29421487603 is the average for d', 
           '1.51074380165 is the average for e', 
           '1.46997245179 is the average for f', 
           '1.15950413223 is the average for g', 
           '1.94159779614 is the average for h', 
           '1.48236914601 is the rainfall average for i',
           '1.2914600551 is the average for j']

我想要做的是只取列表中的所有整数,即 2.06555、1.222 等。 将它们全部相加,然后将总和除以列表中的项目数并打印结果

目前我有一个总变量

total= sum(int(average))/len(average)
print total 

但是我的代码似乎不允许我挑选出所有整数并将它们相加。无论如何我可以只挑选整数来求和然后得到平均值吗?

感谢您的帮助。

【问题讨论】:

  • 我认为您的意思是“实数”而不是“整数”

标签: python list sum average


【解决方案1】:
>>> average = ['2.06556473829 is the average for a', '1.48154269972 is the average for b', '1.56749311295 is the average for c', '2.29421487603 is the average for d', '1.51074380165 is the average for e', '1.46997245179 is the average for f', '1.15950413223 is the average for g', '1.94159779614 is the average for h', '1.48236914601 is the rainfall average for i', '1.2914600551 is the average for j']
>>> avgs = [float(x.split()[0]) for x in average]
>>> sum(avgs)/len(avgs)
1.626446280991

要获取列表中数字的int 值的平均值:

>>> avgs = [ int(float(x.split()[0])) for x in average]
>>> sum(avgs)/float(len(avgs))
1.2

您也可以使用regex 来获取整数:

>>> import re
>>> [ int(re.search(r'\d+',x).group(0)) for x in average]
[2, 1, 1, 2, 1, 1, 1, 1, 1, 1]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多