2013-07-02 31 views
0

我使用下面的代碼(簡化了這個問題):蟒紋問題

t1=['1.99','2','133.37'] 
t2=['4.98','5','11116.98'] 
t3=list(zip(t1,t2)) 
t4=[] 
for num1,num2 in t3: 
    t4.append(float(num1)+float(num2)) 
print('The sum is='+ ":".join(map(str,t4))) 
# output is -> The sum is=6.970000000000001:7.0:11250.35 

但我想輸出到如下是:

The sum is=6.970000:7.000000:11250.350000 
# i.e. six digits ONLY after decimal point 

我該怎麼辦呢?

+0

+1我看不出有任何理由爲什麼有人downvoted初學者問題。 – pepr

回答

2

使用format

>>> format(5.2, '.6f') 
'5.200000' 

.6手段「6位小數」和f意味着一個浮點數。

要把它放到你的現有代碼,使用lambda作爲參數map而非str

print('The sum is=' + ":".join(format(n, '.6f') for n in t4)) 
+0

可能更好地使用genex而不是'map()'。 –

+0

'map('{:。6f}'。format,t4)'應該可以工作 – Volatility

+0

@Ignacio:已添加。 – icktoofay

0
t4.append("%.6f" % (float(num1)+float(num2))) 

print('The sum is=' + ":".join(map(lambda n: format(n, '.6f'), t4))) 

你也可以用生成器表達式替換你map通話

"%.6f" % anumber表示將號碼轉換爲f號碼,號碼在.

1
print('The sum is={:.6f}:{:.6f}:{:.6f}'.format(*t4)) 
0

格式化後6數字ň格式可以用%.6f進行長達6位小數

t1=['1.99','2','133.37'] 
t2=['4.98','5','11116.98'] 
t3=list(zip(t1,t2)) 
t4=[] 
print('The sum is='+ ":"), 
for num1,num2 in t3: 
    each_sum = float(num1)+float(num2) 
    print(":%.6f"%each_sum),