问题
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
this is the code i tried
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))
回答1:
Try this:
#!/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))
Top marks for using with
!
You can learn more about islice() and List Comprehensions from the documentation.
Have fun with Python
:-)
回答2:
This "CSV" file is rather simple, so it doesn't look like you need to use the CSV module.i.strip().isdigit()
skips the leading 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
I'm aware that this list comprehension has now become so complex that it may not be the best solution anymore, but I'll let it stay in case anyone is interested in using something like it. It is, after all, the most compact solution and you don't have to use an extra module.
来源:https://stackoverflow.com/questions/16522767/need-help-on-average-python