Home > Net >  Faster list manipulation
Faster list manipulation

Time:11-24

I have a large numpy array whNumPylements I individually want to multiply with other indexes and then sum up. My current code is relatively slow, does anyone have an idea how I could make it faster:

result = 0
n = 1
int_array = np.array((3,16,3,29,36))
for i in int_array:
    result  = int(i) * n
    n *= 10

CodePudding user response:

In every iteration 10 * prev(10 * ...), So you can use 10 ^ [0, 1, 2, ...] = [1, 10, 100, ...] with numpy.array & numpy.power. Then you need [1*int_arr[0], 10*int_arr[1], ...]. At the end, you need numpy.sum().

res = (np.power(10, np.arange(int_array.shape[0])) * int_array).sum()

print(res)

Output:

389463

CodePudding user response:

I think i have understood that you want to progressively multiply each number of the array by n, and n is going to be multiplied by 10 each loop. Is that is what you want to do, I think there is nothing much to do. The only thing is that you dont need to convert i to an int, as i is already one

  • Related