【问题标题】:Need Help on Average Python [closed]在普通 Python 上需要帮助 [关闭]
【发布时间】:2013-05-13 13:03:28
【问题描述】:

求字段 [quant] 中大于或等于 (337) 的值的平均值 这是量化领域

quant
100
7
109
204
28
292
105
254
441
401
410
14
15
51
96
403
75
31
109
17

这是我尝试过的代码

import csv

total = count = 0

with open('3111111a.csv', newline='') as f:
    reader = csv.reader(f)
    next(reader, None)  

    for row in reader:
        total += float(row[4])
        count += 1

    if count:
        average = total / count
        print('The average of the values is {}'.format(average))

【问题讨论】:

  • 你不应该只取大于或等于 337 的平均值吗?
  • 对不起......我是一个初学者......我正在努力解决这个问题。是的,我应该,但我的代码是错误的......我认为
  • sum([x for x in l if x >= 337])/len(l) where l is you quant list
  • @Denis:这是错误的答案。对所有数字 geq 337 进行平均意味着您必须除以数字 geq 337 的数量。
  • 您的代码存在缩进问题。缩进在 Python 中很重要,因此请检查我的编辑是否正确并修复所有需要修复的内容,以便您的代码看起来与您运行的相同。

标签: python average


【解决方案1】:

试试这个:

#!/bin/env python
import csv
from itertools import islice

total = count = 0

with open('3111111a.csv', newline='') as f:
    reader = csv.reader(f)
    # `isslice` will skip any header/title row.
    # Generates a list of integers from the fourth CSV value
    numbers = (int(row[4]) for row in islice(reader, 1, None))
    # Generates another list of values that are >= 337
    gt337 = [i for i in numbers if i >= 337]

# Sums all the numbers in our list then divides by the number to get the average
print (sum(gt337)/len(gt337))

使用with的最高分!

您可以从文档中了解有关islice()List Comprehensions 的更多信息。

Python 玩得开心:-)

【讨论】:

  • 我在 print 和 sum 之间不断收到错误“无效语法”。最后一行
  • 抱歉 - 在int(row[4]) 部分错过了)。现已修复。
  • 而不是执行两次int 并手动跳过标题,numbers = (int(row[4]) for row in islice(reader, 1, None)) - 然后从中创建列表 - gt337 = [i for i in numbers if i >= 337] 等...
  • 我仍然遇到同样的问题
  • @Jake 您正在使用 Python 3,其中 print 是一个函数(不是语句),因此将最后一行更改为 print(sum(numbers) / len(numbers))
【解决方案2】:

这个“CSV”文件相当简单,所以看起来您不需要使用 CSV 模块。
i.strip().isdigit() 跳过前导 quant

>>> [i for i in open("average.csv", "r")]
['quant\n', '100\n', '7\n', '109\n', '204\n', '28\n', '292\n', '105\n', '254\n', '441\n', '401\n', '410\n', '14\n', '15\n', '51\n', '96\n', '403\n', '75\n', '31\n', '109\n', '17\n']
>>> l = [int(i.strip()) for i in open("average.csv", "r")\
...         if i.strip().isdigit() and int(i) >= 337]
>>> l
[441, 401, 410, 403]
>>> sum(l) / float(len(l))
413.75

我知道这个列表理解现在变得如此复杂,以至于它可能不再是最好的解决方案,但我会保留它,以防有人有兴趣使用类似的东西。毕竟,它是最紧凑的解决方案,您不必使用额外的模块。

【讨论】:

  • 如果字符“quant”是 csv 的一部分怎么办?
  • 如果 'quant' 是标题行将失败。此外,从 OP 代码的外观来看,它们的值是行中的第 4 个 (row[4]),并且他们发布了一个简化的 CSV 示例。
  • @ilmiacs 是的,这可以通过在if int(i) >= 337 后面添加and <condition> 来忽略,但是没有说明这个词(“quant”)可能是什么形式,或者它是否总是“量化”。
猜你喜欢
  • 1970-01-01
  • 2015-09-24
  • 2014-11-04
  • 2012-12-21
  • 2014-04-05
  • 2011-09-15
  • 2021-11-12
  • 2014-09-22
  • 2014-08-31
相关资源
最近更新 更多