-3

I have a list lt[][] which contains float values.Now when I try to find the average or mean of these float values I get an error as either float object has no attribute mean or float object is not iterable. The code that I am using is:

for i in range(100):  
    acc_pos = marks[i][5] # list of float values
    pos_acc.append((sum(acc_pos))/(len(acc_pos))) # when used then 2nd error comes
    neg_acc.append(acc_pos.mean()) # when used then 1st error comes

NOTE: I am not using both the method together but either of them.The error comes according to the line I used

UPDATE: marks is a list of list-something like [78.3,[1,0,,1...],...]. So by writing marks[i][5], I am trying to access 0 index element for each row.

Matthias Urlichs
  • 2,301
  • 19
  • 29
user2916886
  • 847
  • 2
  • 16
  • 35

2 Answers2

3

I thnik the problem is at the second line.

acc_pos = marks[i][0]

That line does not put a list of floats in acc_pos, it puts only one float at pos[i][0] in matrix.

Replace it with

acc_pos = marks[i]
Valdrinium
  • 1,398
  • 1
  • 13
  • 28
0

The way to calculate the mean over a list of floats is solved in this stackoverflow question.

If you were looking for the overall mean of the list of lists, the below will work even if the lists are of different lengths:

numerator = reduce(lambda x, y: x + sum(y), marks, 0.0)
denominator = reduce(lambda x, y: x + len(y), marks, 0.0)
result = numerator / denominator
5.0  # result

As a note for debugging (don't have the rep to comment on a question apparently) -- Python is an interpreted language and will not give compiler errors on your program. Python's interactive console makes debugging easy. You could have at least diagnosed your error message above by doing the following in the console:

# (0) define the 'marks' test variable
marks = [[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]

# (1) do the fist iteration of the loop by hand
i = 0
acc_pos = marks[i][0]
acc_pos.mean()  # Error occurs

# (2) print out the variable
acc_pos

# At this point you realize acc_pos is a float not a list

Helpful resources: tutorial for Python 2, and for Python 3. They are faster than the tutorial sites like Udemy or Code Academy if you already know another language.

Community
  • 1
  • 1
slushy
  • 3,277
  • 1
  • 18
  • 24