1

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

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))
4

2 回答 2

5

尝试这个:

#!/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:-)

于 2013-05-13T13:26:27.867 回答
1

这个“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

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

于 2013-05-13T13:19:20.430 回答