如何变换花车为整数的列表

问题描述 投票:0回答:4

下面我有这需要它们是浮动系数的列表的代码,我想反过来说实际上是整数的,为整数(例如2.0我想成为仅有2)。

所以,我有下面的代码和的3个打印功能输出是:[ 0. 0. -0. 0. -0. -0. -0. 0. 0.5 0. ]

0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0

[ 0. 0. 0. 0. 0. 0. 0. 0. 0.5 0. ]。因此,基于印刷,它进入“if”语句,这意味着它证实了我的系数实际上是整数(我也曾尝试“is_integer”功能,得到了相同的结果),但由于某种原因,它不将它们转换为整数。有人可以帮我吗?谢谢!

def function(coeffs):    
    coeffs = np.round(coeffs,2)
    print(coeffs)
    for w in range(len(coeffs)):
        if coeffs[w]-int(coeffs[w])==0.0:
            coeffs[w] = int(coeffs[w])
            print(coeffs[w])
    print(coeffs)
python
4个回答
1
投票

您的数据看起来是可能进来作为numpy的阵列,具有浮动D型。您正在分配整数回到这个numpy的float数组。这不会更改个别条目的类型,如numpy的数组只有一个类型的阵列中的所有条目。

您可以产生与结果的新的Python列表。

像这样的工作:

result = [ int(x) if x-round(x)<0.0001 else x for x in np.array([1.1, 2.0, 3]) ]

0
投票

这样做的一个方法是检查如果两个ceilfloor函数返回相同的值。对于这样的花车应该是相同的。

import math
...
for w in range(len(coeffs)):
    if math.floor(coeffs[w]) == math.ceil(coeffs[w]):
        print(int(coeffs[w]))

0
投票

您可以在回路中添加类型检查的条件,如if int(coeffs[w]) == coeffs[w],因为我怀疑这将是作为一个解决方案更健壮。

另外,我建议建立一个新的列表或使用拉姆达为修饰列表(或在这种情况下,numpy阵列,其中有一组数据类型)在同一时间,你访问它,通常带来的陷阱。

以下应很好地工作。

new_coeffs = []
def function(coeffs):    
    coeffs = np.round(coeffs,2)
    print(coeffs)
    for w in range(len(coeffs)):
        if int(coeffs[w]) == coeffs[w]:
            new_coeffs.append(int(coeffs[w]))
        else:
            new_coeffs.append(coeffs[w])
    print(new_coeffs)

这将产生以下结果,我怀疑是你所需要的。

>>> new_coeffs = []
>>> a = [1.0, 2.0, 4.1, -8.0, -1.3]
>>> function(a)
[ 1.   2.   4.1 -8.  -1.3]
[1, 2, 4.1, -8, -1.3]

0
投票

这是使用列表理解的好地方。我不明白为什么你给的代码不能正常工作,但我可以给你的代码这将使它发挥作用。

coeffs = [int(x) if x.is_integer() else x for x in coeffs]

这条线经过的coeffs阵列和每x,它会检查它是否与你提到的is_integer()功能的整数。如果是,添加int(x),否则浮动本身添加。

© www.soinside.com 2019 - 2024. All rights reserved.