2024-06-16 13:22:11 发布
网友
我该怎么把我刮下来的浮点数加起来
for post in posts: numberOfItems = numberOfItems + 1 print(numberOfItems) value = float(re.sub(r"[^\d.]", "", post.text)) print("Chaos orbs: %s" % value) print(value)
像这样,打印(value1+value2+value3),但是,这是一个随机的数量,我不知道,所以我不能做变量
您想实现以下目标:
post="1.0 2.0 3.0\n 1.5 2.3" print sum(map(float,post.split()))
不清楚要刮取什么,但这应该提取数值:
import re s = "abc 12.25 def 20 df20.5 $10,000.50" >>> re.findall(r"([\d.?]+)", re.sub(",", "", s)) ['12.25', '20', '20.5', '10000.50']
此正则表达式从字符串中删除逗号,并将结果传递给另一个正则表达式,该正则表达式查找所有可能有或可能没有十进制(.?)的数字(\d)
.?
\d
整数字符串列表可以很容易地求和:
>>> sum(float(n) for n in re.findall(r"([\d.?]+)", re.sub(",", "", s))) 10053.25
然后在外循环中求和:
total_sum = 0 for post in posts: ... total_sum += sum(float(n) for n in re.findall(r"([\d.?]+)", re.sub(",", "", s))) ...
使用sum():
sum()
for post in posts: ... # rest of code snippet you posted print(sum(float(re.sub(r"[^\d.]", "", post.text)) for post in posts))
在for循环外,将所有值相加并打印出总和
或者,如果您希望以某种方式使用现有for循环以避免重复两次,那么:
summed_values = 0 for post in post: ... # rest of code snippet you posted summed_values += value
您想实现以下目标:
不清楚要刮取什么,但这应该提取数值:
此正则表达式从字符串中删除逗号,并将结果传递给另一个正则表达式,该正则表达式查找所有可能有或可能没有十进制(
.?
)的数字(\d
)整数字符串列表可以很容易地求和:
然后在外循环中求和:
使用
sum()
:在for循环外,将所有值相加并打印出总和
或者,如果您希望以某种方式使用现有for循环以避免重复两次,那么:
相关问题 更多 >
编程相关推荐