-3

What is the average value of the numbers in the field [quant] in the range (198) and (272) inclusive

quant
95
189
176
200
177
340
205
203
284
88
109
83
360
67
250
56
111
439
354
143

this is the code that i tried. Above is the [quant] field from where i need to find the average.

word_file = open('300000a.csv','r')

firstLine = True 
for line in word_file:
    if firstLine:
        firstLine = False
        continue
    line = line.strip()
    line = line.split (",")
    field = int(line[0])

TotalMetalCount +=1
if  field >198 or field <272:
  metalCounts += 1
else:
    metalCounts = 1


countT +=1
if field >198 or field <272:
        count += 1
  • [`reduce(lambda x, y: x + y, l) / len(l)`](http://stackoverflow.com/questions/9039961/finding-the-average-of-a-list) – Grijesh Chauhan May 14 '13 at 12:23
  • 3
    @GrijeshChauhan Please don't suggest `reduce` when you can just use `sum` – jamylak May 14 '13 at 12:25
  • @LevLevitsky yeah... not quite sure why it's been asked again. Anyway, it must be part of a class/assignment, but http://stackoverflow.com/questions/16522767/need-help-on-average-python asked it much better - so would suggest to the OP to read that one... – Jon Clements May 14 '13 at 12:36
  • I have read your code some times, but I don't known what is the meaning of your code and the variable. – Tanky Woo May 14 '13 at 12:41
  • im a beginner finding it really tricky :/ – user2370772 May 14 '13 at 12:57
  • The same user has already asked this question, only with minor differences: http://stackoverflow.com/questions/16486849/finding-average-value-of-numbers-in-range-298-272 – timss May 14 '13 at 13:34

2 Answers2

2

You can calculate the average of a list using sum and dividing it by the length.

float(sum(my_list))/len(my_list)

If you need to grab only a few specific items and extract the average based on those you can slice the array.

print(float(sum(my_list[198:272]))/len(my_list[198:272]))

If you have a list that contains strings, and not integers you need to convert them to a list of integers before you can use sum.

my_list_of_integers = [int(i) for i in my_list[198:272]
print(float(sum(my_list_of_integers))/len(my_list_of_integers]))
eandersson
  • 25,781
  • 8
  • 89
  • 110
0

If you are going to be doing much more numerics than this, you should use numpy. Then there will be various ways of reading CSV files as arrays. Those arrays have a .mean() method, which does what you think it does.

(But if you don't do more numerics, then @eandersson answer is more proportionate).

Adrian Ratnapala
  • 5,485
  • 2
  • 29
  • 39