views:

113

answers:

7

I have a string like this "1 1 3 2 1 1 1 2 1 1 1 1 1 1 1 1,5 0,33 0,66 1 0,33 0,66 1 1 2 1 1 2 1 1 2 0,5 0,66 2 1 2 1 1 1 0 1".

How to add elements to each other in python ?

I've tried :

list = []
for x in str.replace(' ', ''):
    list.append(x)
sum = 0
for y in list:
    sum = sum + double(x)

but I'm getting errors constantly.

+4  A: 

The "python-esque" way of doing it:

sum([float(num) for num in str.replace(',', '.').split(' ')])

Makes a list by splitting the string by spaces, then turn each piece into a float and add them up.

David
David: You have to take into account the random commas.
Xavier Ho
What's random about the commas?
dash-tom-bang
David: Why not just drop the list and use generator syntax?
Xavier Ho
NB: split uses ' ' by default. No need to specify that explicitly
inspectorG4dget
+2  A: 

Edit: If David's guess was right such that you need decimals:

>>> from math import fsum
>>> fsum(float(n) for n in input.replace(',', '.').split())
45.640000000000001

Note I'm using math.fsum() to preserve floating point loss.

Xavier Ho
The commas in the string are decimal points, I assume.
David
Huh? You lost me. Does that mean we should use `float` instead?
Xavier Ho
+7  A: 
print sum(float(x.replace(',', '.')) for x in str.split(' '))

outputs:

45.64
Eddy Pronk
+1  A: 

If I understand what you want, then try this:

list = []
for x in str.replace(',', '.').split():
    list.append(x)
sum = 0
for x in list:
    sum = sum + float(x)
Artelius
+2  A: 
my_string = "1 1 3 2 1 1 1 2 1 1 1 1 1 1 1 1,5 "
            "0,33 0,66 1 0,33 0,66 1 1 2 1 1 2 "
            "1 1 2 0,5 0,66 2 1 2 1 1 1 0 1"

my_string = my_string.replace(',', '.')

value = sum([float(n) for n in my_string.split()])
dash-tom-bang
+1  A: 

Ok this worked :

sum(float(n) for n in str.replace(',','.').split())
owca
That's identical to my answer (and many others' now it seems). Feel free to accept one of our answers!
Xavier Ho
yeah I know, you must've written yours when I was creating mine :)
owca
+4  A: 

Let's not be so ethno-centric. ',' is a legitimate decimal point for many people. Don't replace it, adapt to it using the locale module:

>>> s = "1 1 3 2 1 1 1 2 1 1 1 1 1 1 1 1,5 0,33 0,66 1 0,33 0,66 1 1 2 1 1 2 1 1 2 0,5 0,66 2 1 2 1 1 1 0 1"
>>> import locale
>>> locale.setlocale(0,"po")
'Polish_Poland.1250'
>>> sum(map(locale.atof, s.split()))
45.639999999999993
Paul McGuire
Then shouldn't the output be `45,639`?
kibibu
The value 45.64 (as I write it) is the value 45.64 regardless of how it is displayed. If you needed to print it back out in the localized format, then wrap it in locale.str(), which in this case would give "45,64".
Paul McGuire