为每个人提供不同的结果?

时间:2015-12-30 03:59:41

标签: python

我尝试在: seprated之间添加逗号分隔值,然后乘以整个值 例如,考虑我的值为1,2,3:4,5,6 我想添加1 + 2 + 3和4 + 5 + 6然后乘以该值的结果,所以答案是6 * 15 = 90

对于我的波纹管数据,我希望结果为7.224,但此脚本会显示61.658886435 我不知道我的脚本'

中有什么问题
ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
x_data = ar.split(":")
x_final = 1
x_add = 0
for i in x_data:
    x_each = i.split(",")
    for j in x_each:
        x_add = x_add + float(j)
    x_final = x_add * x_final

print x_final

有没有可能的方法来获得没有迭代循环的结果?对于上述问题

3 个答案:

答案 0 :(得分:1)

这个问题也可以通过功能性的方式解决:

  1. 您必须将列表中的所有值相乘 - 这是functools.reduce + operator.mul

  2. 的内容
  3. 您必须总结所有内部列表中的所有值 - 这是sum

  4. 的内容

    示例:

    In [5]: ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
    
    In [6]: import operator
    
    In [7]: import functools
    
    In [8]: functools.reduce(operator.mul, (sum(float(x) for x in s.split(',')) for s in ar.split(':')))
    Out[8]: 7.223521582500001
    

答案 1 :(得分:1)

我不一定会推荐这个复杂的表达式,但是您可以使用列表推导来避免for循环:

import operator

ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
reduce(operator.mul, [sum([float(n) for n in e]) for e in [x.split(',') for x in ar.split(":")]], 1)

答案 2 :(得分:0)

在每次迭代中使用错过初始化值为零(x_add = 0)。所以你的脚本添加了以前的值

ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
x_data = ar.split(":")
x_final = 1
for i in x_data:
    x_each = i.split(",")
    x_add = 0             # Here you not initialize it
    for j in x_each:
        x_add = x_add + float(j)
    x_final = x_add * x_final

print x_final
  

!!!来自@ jpmc26和@soon评论。避免使用eval,并符合您的输入字符串格式。   没有循环使用正则表达式来做到这一点

使用正则表达式解决问题而不循环。

ar = "0.212,1.231,0.112:1.001,3.212,0.002:0.002,0.0001,1.1"
import re
ar = "("+ar                      #Add the ( with your data 
ar = re.sub(r",","+",ar)         #Substitute with + instead of ,
ar = re.sub(r"(?=\:|$)",")",ar)  #look ahead for add `)` after colon
ar = re.sub(r"(?<=)\:","*(",ar)  #Replace the color with *

#NOw you data look likes(0.212+1.231+0.112)*(1.001+3.212+0.002)*(0.002+0.0001+1.1)
#Finally evaluvate the string as a expression
print eval(ar)