0

I am trying to normalize lists of numbers using Python. I am aware of this page Normalizing a list of numbers in Python.

def normalize(lst):
     s = sum(lst)
     return map(lambda x: float(x)/s, lst)

raw = [[0.07, 0.14, 0.07], [0.10, 0.05, 0.05]]

for i in raw:
print normalize(i)

The above codes work just fine. But, my data is in the following format:

raw1 = [['0.07', '0.14', '0.07'], ['0.10', '0.05', '0.05']]

for i in raw1:
     print normalize(i)

And, I am getting this error:

TypeError                                 Traceback (most recent call last)
<ipython-input-39-96ae4b221f63> in <module>()
      1 for i in raw1:
----> 2     print normalize(i)

<ipython-input-28-9ad45c58be20> in normalize(lst)
      1 def normalize(lst):
----> 2     s = sum(lst)
      3     return map(lambda x: float(x)/s, lst)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Any suggestions?

Community
  • 1
  • 1
kevin
  • 1,914
  • 4
  • 25
  • 30

1 Answers1

0

So your code works fine until you replace the numbers in the lists with strings.

The obvious fix is to convert those strings to numbers (using float()).

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101