gpt4 book ai didi

python - 将字符串总和打印为 float

转载 作者:太空宇宙 更新时间:2023-11-04 10:31:28 28 4
gpt4 key购买 nike

我正在做一个练习:

Let s be a string that contains a sequence of decimal numbers separated by commas, e.g., s = '1.23,2.4,3.123'. Write a program that prints the sum of the numbers in 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 类(class)的开始阶段,所以此时我只是试图通过初学者级别的解决方案来完成此任务。

最佳答案

是的,显着:

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

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

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

map申请float到每个字符串

>>> 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将字符串解释为 float 元组:

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

关于python - 将字符串总和打印为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26242547/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com