在Python中无需使用for循环对两个数组进行卷积操作。

huangapple go评论59阅读模式
英文:

Convolving two arrays in python without for loops

问题

arr_1 = [21, 28, 36, 29, 40]
arr_2 = [0, 225, 225, 0, 225]

arr_out = [-1, 28, 36, -1, 40]

The output arr_out will have -1 at an index if the product of the elements in arr_1 and arr_2 at that index is 0. Otherwise, the value from arr_1 will be in the output array.

I have implemented a solution using a for loop:

arr_out = [0] * 5

for index, value in enumerate(arr_1):
    if (value * arr_2[index]) == 0:
        arr_out[index] = -1
    else:
        arr_out[index] = value

你是否可以在不使用for循环的情况下实现这一目标?

英文:

I have two arrays(arr_1,arr_2), and need to generate an output(arr_out) as follows:

arr_1 = [21, 28, 36, 29, 40]
arr_2 = [0, 225, 225, 0, 225]

arr_out = [-1, 28, 36, -1, 40]

The outputarr_out should have -1 at an index if the product of the elements in arr_1 and arr_2 at that index is 0. Otherwise, the value from arr_1 should be in the output array.

I have implemented a solution using a for loop:

 arr_out = [0] * 5

 for index, value in enumerate(arr_1):
    if (value * arr_2[index]) == 0:
        arr_out[index] = -1
    else:
        arr_out[index] = value

Is it possible to achieve this without using a for loop?

答案1

得分: 4

你可以使用列表推导和zip函数来实现这个:

arr_out = [-1 if (x * y) == 0 else x for x, y in zip(arr_1, arr_2)]

这将消除对for循环和enumerate的需求。我们使用了zip函数,它将两个列表逐个元素地组合在一起。然后,我们使用列表推导来遍历组合的元素并执行所需的操作。

英文:

You can achieve this using list comprehensions along with the zip function:

arr_out = [-1 if (x * y) == 0 else x for x, y in zip(arr_1, arr_2)]

This will remove the need for for loops as well as enumerate. We're using the zip function, which combines two lists element-wise. Then, we use a list comprehension to loop through the combined elements and perform the desired operation.

答案2

得分: 1

你可以使用 [tag:numpy] 并将 list 转换为 numpy.array,然后使用 numpy.where

import numpy as np
arr_1 = [21, 28, 36, 29, 40]
arr_2 = [0, 225, 225, 0, 225]

np_arr_1 = np.array(arr_1)
np_arr_2 = np.array(arr_2)
arr_out = np.where(np_arr_1 * np_arr_2 == 0, -1, np_arr_1)
print(arr_out)

输出:

[-1 28 36 -1 40]
英文:

You can use [tag:numpy] and convert list to numpy.array then use numpy.where.

import numpy as np
arr_1 = [21, 28, 36, 29, 40]
arr_2 = [0, 225, 225, 0, 225]

np_arr_1 = np.array(arr_1)
np_arr_2 = np.array(arr_2)
arr_out = np.where(np_arr_1 * np_arr_2 == 0, -1, np_arr_1)
print(arr_out)

Output:

[-1 28 36 -1 40]

huangapple
  • 本文由 发表于 2023年4月11日 03:52:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980255.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定