使用枚举函数,有没有一种方法可以同时引用索引而不引用元素?

时间:2020-07-23 02:49:23

标签: python

我需要编写一个函数,该函数接收一个整数数组并返回一个数组,该数组由该数组中除该索引处的数字以外的所有数字的乘积组成

例如,给定:

[3, 7, 3, 4]

该函数应返回:

[84, 36, 84, 63]

通过计算:

[7*3*4, 3*3*4, 3*7*4, 3*7*3]

如果数组不包含重复项,我编写的函数将起作用,但是我似乎无法弄清楚如何引用跳过索引而不跳过数组中与索引值相同的任何数字。

def product_of_all_other_numbers(arr):
     product_array = []
     for idx, val in enumerate(arr):
         running_count = 1
         for n in arr:
             if n != arr[idx]:
                 running_count *= n
         product_array.append(running_count)
     return product_array

枚举是否可行?还是应该开始探索另一条路线?

2 个答案:

答案 0 :(得分:4)

我似乎无法弄清楚如何在没有索引的情况下引用跳过索引 也跳过数组中与 索引。

不需要比较该索引处的,您只关心索引。所以您的内循环可能是这样的:

def product_of_all_other_numbers(arr):
     product_array = []
     for idx, val in enumerate(arr):
         running_count = 1
         for i, n in enumerate(arr):
             if i != idx:
                 running_count *= n
         product_array.append(running_count)
     return product_array

请注意,对于此问题,有更有效的解决方案,但这可以解决您当前的问题。

答案 1 :(得分:2)

您可以使用numpy prod方法并进行列表切片

In [91]: import math
In [92]: def product_of_all_other_numbers(lst):
    ...:     data = []
    ...:     for i in range(len(lst)):
    ...:         data.append(math.prod(lst[:i] + lst[i+1:]))
    ...:     return data
    ...:

In [93]: product_of_all_other_numbers([3, 7, 3, 4])
Out[93]: [84, 36, 84, 63]