Skip to main content
 首页 » 编程设计

python之使用 zip 函数并使用 getcontext().prec =2 获取错误

2025年05月04日15powertoolsteam

我在尝试使用 getcontext().prec = 2 函数时遇到问题,试图获得只有 2 位小数的小数结果。我已经尝试了几种变体,但不知道为什么我不能在我的一个列表中将 float 转换为字符串。我是使用 Python (2.6) 的新手,还没有找到解决方案。在此先感谢您的帮助。

from __future__ import division 
from decimal import * 
 
getcontext().prec = 2 
 
list_a = ['abc','def','ghi'] 
list_b = [123, 534, 345] 
list_c = [Decimal(str(1/6)), Decimal(str(1/1234)), Decimal(str(2/9))] 
 
for r,c,p in zip(list_a, list_b, list_c): 
  print '{0} goes with {1} and with {2}%.'.format(r,c,p) 

返回

SyntaxError: Invalid syntax 

如果我从打印行中删除 str() ,结果将被打印出来,但没有小数位数限制。如果我使用 Decimal() - 先不使用 str,我得到

'first convert the float to a string'.  

有什么见解吗? 干杯

请您参考如下方法:

Decimal(str((2/9)) 

应该是

Decimal(str(2/9)) 

示例中显示的代码中有一个未闭合的)。

只显示两位小数:

from __future__ import division 
from decimal import * 
 
getcontext().prec = 2 
 
list_a = ['abc','def','ghi'] 
list_b = [123, 534, 345] 
list_c = [Decimal(str(1/6)), Decimal(str(1/1234)), Decimal(str(2/9))] 
for r,c,p in zip(list_a, list_b, list_c): 
  print '{0} goes with {1} and with {2:.2f}%.'.format(r,c,p)