简体   繁体   English

如何在数组上循环 function

[英]How to loop a function over a array

So here is the thing I would like to write a function that finds a specific set of numbers.所以这就是我想写一个找到一组特定数字的 function 的东西。 So I have tries a few different ways所以我尝试了几种不同的方法

I tried this way the Boolean way and kept getting the arguments我以这种方式尝试了 Boolean 方式并不断获得 arguments

import numpy as np
N = np.array([10,1,2,3,4,5,6,7,8,9])
def function(N): 
    e = 0
    for i in range(n): 
        if i % 2 == 0: 
            e += a[i]
             sum(e)

Got the error for the above code TypeError: only integer scalar arrays can be converted to a scalar index得到上述代码的错误TypeError: only integer scalar arrays can be convert to a scalar index

import numpy as np
N = np.array([10,1,2,3,4,5,6,7,8,9])
def function(N):
    filter_arr = []
    for item in N:
        if(N% 2 ==0):
            filter_arr.append(True)
        else:
            filter_arr.append(False)
newarr = N[filter_arr]
print(sum(newarr))

So here is another attempt to get it right所以这是另一种正确的尝试

import numpy as np
N = np.array([10,1,2,3,4,5,6,7,8,9])
def function(N):
    for item in N:
        if(N%2 ==0):
            return False
        else:
            return True
        
even_numbers=filter(function, N)

for N in even_numbers:
    print(N)

I get a numpy.int32 error我收到 numpy.int32 错误

def function(N): 
    e = 1
    for i in range(0): 
        if (i % 2 == 0): 
            e *= N[i]
            print(e)

This is the closest I have gotten with no error but no result.这是我得到的最接近的结果,没有错误但没有结果。 So Looking for some help as to what I am doing wrong.所以寻找一些关于我做错了什么的帮助。

def func(array):
    product = 1
    for i in array:
        if i==0:
            continue
        if i%2==0:
            product *= i
    return product
N = np.array([0,10,1,2,3,4,5,6,7,8,9])
func(N)

Start your variable that will collect your product at 1 since it is a multiplication.开始您的变量,它将在 1 处收集您的product ,因为它是一个乘法。

If the number is 0 I made a condition to pass it, unless you want to get 0s in your algorithm.如果数字为0 ,我设定了通过它的条件,除非您想在算法中得到 0。

i%2==0 is just to check if a number has a rest of 0 when divided by 2 aka modulo . i%2==0只是检查一个数字除以2 aka modulo时的rest0

def func1(array):
    sum1 = 0
    for i in array:
        if i%2==0:
            sum1 += i
    return sum1
N = np.array([0,10,1,2,3,4,5,6,7,8,9])
func1(N)

This code will give you the sum, similar structure, however, 0 s in sum dont matter so you can remove the condition on 0 s.此代码将为您提供总和,类似的结构,但是,总和中的0无关紧要,因此您可以删除0上的条件。

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

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