📜  Python - 浮点字符串列表的总和

📅  最后修改于: 2022-05-13 01:55:42.871000             🧑  作者: Mango

Python - 浮点字符串列表的总和

有时,在使用Python列表时,我们可能会遇到需要在列表中求和的问题。但有时,我们没有自然数,而是字符串格式的浮点数。在 Web 开发和数据科学领域处理数据时可能会出现此问题。让我们讨论解决这个问题的方法。

方法#1:使用sum() + float() + generator
这个问题可以使用 sum函数来解决,我们首先将字符串转换为浮点数,然后在各个 sum函数的函数中传递这个逻辑。

# Python3 code to demonstrate working of
# Summation of float string list
# using sum() + float() + generator
  
# initialize lists
test_list = ['4.5', '7.8', '9.8', '10.3']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Summation of float string list
# using sum() + float() + generator
res_sum = sum(float(sub) for sub in test_list)
  
# printing result
print("The summation of float string list : " + str(res_sum))
输出 :
The original list is : ['4.5', '7.8', '9.8', '10.3']
The summation of float string list : 32.400000000000006

方法#2:使用循环
这是执行此任务的蛮力方法。在此,我们对列表进行迭代,并在迭代期间对列表浮动元素进行转换和求和。

# Python3 code to demonstrate working of
# Summation of float string list
# Using loop
  
# initialize lists
test_list = ['4.5', '7.8', '9.8', '10.3']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Summation of float string list
# Using loop
res_sum = 0 
for ele in test_list: 
    res_sum += float(ele)
      
# printing result
print("The summation of float string list : " + str(res_sum))
输出 :
The original list is : ['4.5', '7.8', '9.8', '10.3']
The summation of float string list : 32.400000000000006