0

Hi i have been trying to get the mean of each sub-list using sum/length.

vectors = [[2.731018, 1.7550012, 2.3455532],
 [2.9210236, 3.2172325],
 [2.9255183, 2.66712, 2.7174947]]  

mean_vec = [sum(i)/len(i) for i in vectors]

Currently i am using the code above, however i am being prompted with this error message:

ZeroDivisionError: division by zero

The list above is just a sample. i have a much larger list of numbers. please advice me on how i should solve this

Cua
  • 129
  • 9

1 Answers1

2

Your provided code mean_vec = [sum(i)/len(i) for i in vectors] can fail in certain scenarios

  • [] #an empty list

Please add len(i) != 0 in your code as show below

mean_vec = [sum(i)/len(i) for i in vectors if len(i) != 0]
slider
  • 12,810
  • 1
  • 26
  • 42
Shivam Seth
  • 677
  • 1
  • 8
  • 21