需要有关普通Python的帮助

时间:2013-05-13 13:03:28

标签: python average

在[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))

2 个答案:

答案 0 :(得分: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玩得开心: - )

答案 1 :(得分: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

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