选择字符串的一部分进行计算(python)

时间:2012-06-26 18:13:58

标签: python

我正在开展一个有趣的项目,我将进行一些计算,我需要一些帮助。

我的程序中的一个模块:

def ARK(rawArk):
    refArk = rawArk/200
    arkTrit = refArk*300
    arkMeg = refArk*333
    arkZyd = refArk*166
    print "Totals from your Arkonor:"
    print "Tritanium=", arkTrit
    print "Megacyte=", arkMeg
    print "Zydrine=", arkZyd
    return arkTrit, arkMeg, arkZyd

现在它正在做简单的除法和乘法。我想做的是能够用剩余的东西做到这一点。

因此,如果'refArk = rawArk / 200'总共给出16.3,我希望能够将16.0和0.3分开,并将它们作为单独的变量用于单独的计算。

到目前为止:

def ARK(rawArk):
    refArk = float(rawArk/200)
    arkTrit = refArk*300
    arkMeg = refArk*333
    arkZyd = refArk*166
    print "Totals from your Arkonor:"
    print "Tritanium=", arkTrit
    print "Megacyte=", arkMeg
    print "Zydrine=", arkZyd
    strval = str(refArk)
    head,tail = strval.split(".")
    whole = float(head)
    frac = float("."+tail)
    print whole
    print frac
    return arkTrit, arkMeg, arkZyd

def main():
    rawArk=input("How much Arkonor?")
    ARK(rawArk)
    return

main()

使用'450'作为我的输入值

返回

How much Arkonor?450
Totals from your Arkonor:
Tritanium= 600.0
Megacyte= 666.0
Zydrine= 332.0
2.0
0.0

2.0是正确的,但0.0应该是0.25

从'rawArk / 200'中删除float()会发出错误:

How much Arkonor?450
Totals from your Arkonor:
Tritanium= 600
Megacyte= 666
Zydrine= 332

Traceback (most recent call last):
  File "E:\eve stuff\Calculator\test.py", line 23, in <module>
    main()
  File "E:\eve stuff\Calculator\test.py", line 20, in main
    ARK(rawArk)
  File "E:\eve stuff\Calculator\test.py", line 11, in ARK
    head,tail = strval.split(".")
ValueError: need more than 1 value to unpack

4 个答案:

答案 0 :(得分:1)

可能是第一次使用round函数然后使用split

refArk = refArk.split(".")

答案 1 :(得分:1)

数字上

val1 = 22.0
val2 = 7.0
whole,frac = divmod(val1,val2)
frac = frac/val1

有点黑客但有字符串

val = 22.0/7.0
strval = str(val)
head,tail = strval.split(".")
whole = float(head)
frac = float("."+tail)

无论如何

>>> frac
0.14285714286000001
>>> whole
3.0

答案 2 :(得分:1)

为什么不这样做:

intpart=int(variable)
decimalpart=variable-intpart

我会猜测这比投射到字符串然后拆分更有效。

答案 3 :(得分:0)

IDLE的以下会议应该展示如何解决您的问题。

>>> lis=str(refArk).split('.')
>>> lis[-1]='.'+lis[-1]
>>> map(float,lis)
[16.0, 0.3]