需要有关平均Python的帮助 [英] Need Help on Average Python
本文介绍了需要有关平均Python的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在[quant]字段中找到大于或等于(337)的值的平均值 这是量子场
Find the average of the values in the field [quant] greater than or equal to (337) this is the quant field
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))
推荐答案
尝试一下:
#!/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()和<文档中的href ="http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel ="nofollow">列表理解.
与Python
玩得开心:-)
这篇关于需要有关平均Python的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文