将字符串的总和打印为float

时间:2014-10-07 18:17:34

标签: python string decimal floating-point-conversion

我正在进行一项练习:

  

s成为包含十进制数字序列的字符串   用逗号分隔,例如s = '1.23,2.4,3.123'。写一个程序   打印s中的数字总和。

我的解决方案是:

s = '1.23,2.4,3.123'
news = s + ","
value = ""
floatValue = 0


for i in range(len(news)):
    if news[i] != ',':
        value += s[i]
    elif news[i] == ',':
        floatValue += float(value)
        value = ""

print floatValue

我只是想知道是否有更有效的方法来做到这一点?此外,我正处于Python课程的开始阶段,所以在这一点上,我只是尝试使用初学者级解决方案来实现这一目标。

5 个答案:

答案 0 :(得分:2)

是的,非常重要:

>>> s = '1.23,2.4,3.123'
>>> sum(map(float, s.split(",")))
6.753

这使用str.split将字符串分成数字:

>>> s.split(",")
['1.23', '2.4', '3.123']

mapfloat应用于每个字符串

>>> map(float, s.split(","))
[1.23, 2.4, 3.123]

sum加总。


由于有几个答案略有不同的方法,我想我会测试它们,看看哪个最有效:

<强> 2.7.6

>>> import timeit
>>> def f1(s):
    return sum(map(float, s.split(",")))

>>> def f2(s):
    return sum(float(x) for x in s.split(","))

>>> def f3(s):
    return sum([float(x) for x in s.split(",")])

>>> timeit.timeit("f1(s)", setup="from __main__ import f1, f2, f3;s='1.23,2.4,3.123'")
2.627161979675293
>>> timeit.timeit("f2(s)", setup="from __main__ import f1, f2, f3;s='1.23,2.4,3.123'")
2.805773973464966
>>> timeit.timeit("f3(s)", setup="from __main__ import f1, f2, f3;s='1.23,2.4,3.123'")
2.6547701358795166

<强> 3.4.0

>>> timeit.timeit("f1(s)", setup="from __main__ import f1, f2, f3;s='1.23,2.4,3.123'")
2.3012791969995305
>>> timeit.timeit("f2(s)", setup="from __main__ import f1, f2, f3;s='1.23,2.4,3.123'")
3.1761953750028624
>>> timeit.timeit("f3(s)", setup="from __main__ import f1, f2, f3;s='1.23,2.4,3.123'")
3.1163038839986257

Ashwini的奖金回合( 3.4.0 ):

>>> from ast import literal_eval
>>> def f4(s):
    return sum(literal_eval(s))

>>> timeit.timeit("f4(s)", setup="from __main__ import f1, f2, f3, f4;s='1.23,2.4,3.123'")
23.054055102998973
>>> timeit.timeit("f1(s)", setup="from __main__ import f1, f2, f3, f4;s='1.23,2.4,3.123'")
2.2302689969983476

使用ast.literal_eval将字符串解释为浮点元组:

>>> literal_eval('1.23,2.4,3.123')
(1.23, 2.4, 3.123)

答案 1 :(得分:1)

s = '1.23,2.4,3.123'

短而甜蜜:

print sum(map(float, s.split(',')))

初级水平:

total = 0
for f in s.split(','):
    total += float(f)
print total

答案 2 :(得分:1)

s = '1.23,2.4,3.123'

使用生成器表达式以避免在Python 2和3中不必要地实现列表。由于其可读性提高,这种用法通常取代map

sum(float(n) for n in s.split(','))

返回

6.7530000000000001

在Python 3中,map返回一个迭代器,因此它具有大致相同的性能:

sum(map(float, s.split(',')))

但是在Python 2中,它会不必要地创建一个列表作为中间步骤。

样式指南更喜欢生成器表达式和列表推导到mapfilter,例如见Google's Python style guide

  

列表推导和生成器表达式提供了一种简洁有效的方法来创建列表和迭代器,而无需使用map(),filter()或lambda。

They were created with the intention of reducing the need for map and filter.

答案 3 :(得分:0)

您可以使用str.split将字符串拆分为,,然后将任何索引转换为浮点数!

>>> sum([float(i) for i in s.split(',')])
6.753

答案 4 :(得分:0)

可以这样做:

s = '1.23,2.4,3.123'
val = sum([float(x) for x in s.split(',')])
相关问题