Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 对列表应用算术运算后的十进制值_Python - Fatal编程技术网

Python 对列表应用算术运算后的十进制值

Python 对列表应用算术运算后的十进制值,python,Python,在我现在获取整数时,如何将当前值1和当前值2变量的值作为十进制数获取?在2.7中,将整数除以整数将生成整数。比如说, present_values = random.sample(xrange(1,1000),5) print present_values present_values1 = [(x / 9) * 5 for x in present_values] print (present_values1) present_values2 = [(x / 9)

在我现在获取整数时,如何将当前值1和当前值2变量的值作为十进制数获取?

在2.7中,将整数除以整数将生成整数。比如说,

   present_values = random.sample(xrange(1,1000),5)
   print present_values
   present_values1 = [(x / 9) * 5 for x in present_values]
   print (present_values1)
   present_values2 = [(x / 9) * 4 for x in present_values]
   print present_values2
为了使算术运算不产生整数,它的至少一个操作数必须是非整数

在对其进行算术运算之前,将当前值转换为小数列表

>>> 35 / 9
3
现在您的结果将是小数。示例输出:

import random
from decimal import Decimal

present_values = random.sample(xrange(1,1000),5)

#choose one:
present_values = map(Decimal, present_values) 
#or 
present_values = [Decimal(x) for x in present_values]

print present_values
present_values1 = [(x / 9) * 5 for x in present_values]
print (present_values1)
present_values2 = [(x / 9) * 4 for x in present_values]
print present_values2
如果您的字面意思不是“Decimal数据类型,可在
Decimal
模块中找到”,而是通常的意思是“可以表示具有小数点的数字的任何数字数据类型”,那么您可以对浮点进行同样的操作

[Decimal('209'), Decimal('15'), Decimal('372'), Decimal('367'), Decimal('516')]
[Decimal('116.1111111111111111111111111'), Decimal('8.333333333333333333333333335'), Decimal('206.6666666666666666666666666'), Decimal('203.88888888888888888888
88889'), Decimal('286.6666666666666666666666666')]
[Decimal('92.88888888888888888888888888'), Decimal('6.666666666666666666666666668'), Decimal('165.3333333333333333333333333'), Decimal('163.11111111111111111111
11111'), Decimal('229.3333333333333333333333333')]

替代方法:在3.X中,整数除以整数可能会导致非整数。您可以通过执行以下操作将此行为向后移植到2.7:

present_values = [float(x) for x in present_values]
然后,代码的其余部分将生成“十进制”输出,而无需进行任何其他更改

from __future__ import division