在列表中将除零等于零

时间:2018-06-10 13:39:37

标签: python numpy divide-by-zero

我有一个列表L,我想为每个元素const/L_j计算并获得一个包含元素M的新列表M_j = const/L_j。但是,有L_j个元素为零。在这种情况下,最好将这种除法分配为零。我已将此脚本设为下面但速度很慢。

temp = np.zeros((self.n_features, 1))
for t in range(self.n_features):
    if y[t]!=0:
        temp[t] = x/y[t] 

我的问题与此类似,但我想将其应用于列表中。这是计算列表M的更快方法。

感谢。

5 个答案:

答案 0 :(得分:3)

时间复杂度为O(N)的另一种方式,迭代元素:

M = [0 if l == 0 else constant/l for l in L]

答案 1 :(得分:1)

假设您的数组名为L,您可以执行类似

的操作
M = x/L
M[np.isinf(M)] = 0

即使无限的数量很大,将坏元素归零所需的额外时间也可以忽略不计:

In [20]: L = np.random.randint(0, 2, 100000)

In [21]: %timeit [0 if l == 0 else 10/l for l in L]
34.9 ms ± 2.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [23]: %timeit M = 10/L
263 µs ± 11.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [24]: %timeit M[np.isinf(M)] = 0
983 ns ± 40.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

答案 2 :(得分:0)

def transform_to_M(const, x):
    if x==0:
       return 0
    return const/x

np.fromiter((transform_to_M(const, i) for i in y), float, count=len(y))

答案 3 :(得分:0)

您可以使用math.inf

from math import inf

lst = [2, 1, 0, -1, -2]
const = 1

res = [const / (l or inf) for l in lst]

print(res) # [0.5, 1.0, 0.0, -1.0, -0.5]

答案 4 :(得分:0)

执行此操作的最快,最简单和最pythonic的方法是数组屏蔽:

        function image()
{
$('#myModal').modal('show');

var file = document.getElementById("image").files;
$('#uploadImage').click(function(){

   loadImageFileAsURL();

});

}

 function loadImageFileAsURL()
   {
    var filesSelected = document.getElementById("image").files;

if (filesSelected.length > 0)
{
    var fileToLoad = filesSelected[0];

    if (fileToLoad.type.match("image.*"))
    {
        var fileReader = new FileReader();
        fileReader.onload = function(fileLoadedEvent) 
        {
            var imageLoaded = document.createElement("img");
            imageLoaded.src = fileLoadedEvent.target.result;

             //How to insert Image??
             $('#myModal').modal('hide');
        };
        fileReader.readAsDataURL(fileToLoad);
    }
}
}

这是一个比fuglede代码更快的功能评估。