繁体   English   中英

如何以最快的方式将每个0变成数组列表中的-1?

[英]How to turn every 0 into a -1 in a array list in the fastest way?

我想将大型数组列表的每个0转换为-1。 这已尽快完成。 for循环对我来说非常慢。 我的数组是一个numpy数组。 您知道这个简单问题的更快解决方案吗?

这是示例代码:

test_array=[1 0 0 1 0 0 1 1 0 1 1 0 1 0 0 0]

for index, value in enumerate(test_array):
if value == 0:
    l[index] = -1

test_array=[1 -1 -1 1 -1 -1 1 1 -1 1 1 -1 1 -1 -1 -1]

我的真实列表比本示例中的列表长很多,因此快速解决方案是性能因素。

In [1]: a = np.random.randint(0,2,1000000)  

In [2]: a                                                                      
Out [2]: array([0, 1, 1, ..., 1, 1, 0])

In [3]: %timeit a[a==0]=-1                                                     
1.73 ms ± 50.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

尝试:

import numpy as np
array1 = np.array([1,0 ,0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0])
print (np.where(array1 == 0, -1, array1))

输出:

[ 1 -1 -1  1 -1 -1  1  1 -1  1  1 -1  1 -1 -1 -1]

如果您的test_array是实际列表

test_array = [1,0 ,0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0]
test_array_New = []
for i in test_array:
     if i != 0:
             test_array_New.append(i)
     else:
             test_array_New.append(-1)
test_array_New

输出:

[1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, -1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM