简体   繁体   English

使用枚举 function,有没有办法在不引用元素的情况下引用索引?

[英]Using the enumerate function, is there a way to reference the index without also referencing the element?

I need to write a function that receives an array of integers and returns an array consisting of the product of all numbers in the array except the number at that index我需要编写一个 function 接收整数数组并返回一个数组,该数组由数组中除该索引处的数字之外的所有数字的乘积组成

For example, given:例如,给定:

[3, 7, 3, 4]

The function should return: function 应该返回:

[84, 36, 84, 63]

By calculating:通过计算:

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

The function that I've written will work if the array contains no duplicates, but I can't seem to figure out how to reference skipping the index without also skipping any number in the array with the same value as the index.如果数组不包含重复项,我编写的 function 将起作用,但我似乎无法弄清楚如何引用跳过索引而不跳过数组中与索引具有相同值的任何数字。

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

Is this possible with enumerate or should I start exploring a different route?这可以通过枚举实现还是我应该开始探索不同的路线?

I can't seem to figure out how to reference skipping the index without also skipping any number in the array with the same value as the index.我似乎无法弄清楚如何引用跳过索引而不跳过数组中与索引具有相同值的任何数字。

There's no need to compare the values at that index , you only care about the index .无需比较该index 处的值,您只关心 index So your inner loop could be like this:所以你的内部循环可能是这样的:

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

Note, there are more efficient solutions to this problem, but this addresses your current issue.请注意,此问题有更有效的解决方案,但这解决了您当前的问题。

You could use numpy prod method and list slicing您可以使用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]

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

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