开发者

Python adding elements from string

I have 开发者_如何学Goa 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.


print sum(float(x.replace(',', '.')) for x in str.split(' '))

outputs:

45.64


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.


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


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()])


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.


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)


Ok this worked :

sum(float(n) for n in str.replace(',','.').split())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜