微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将功能应用到arr并打印出来

如何解决将功能应用到arr并打印出来

def kiem_tra_so_hoan_chinh(so):
    if so <= 1:
        return False
    else:
        tong = 0
        for i in range(1,so):
            if so % i == 0:
                tong += i
        if tong == so:
            return True
        else:
            return False

         
        np.random.seed(5)
    arr1 = np.random.randint(low = 1,high = 101,size = 16) 
    arr1=arr1.reshape(4,4)
    arr1

如果包含完美数字,如何将函数用于数组并打印出arr1行 如果我使用kiem_tra_so_hoan_chinh(arr1),则会显示错误

“ ValueError:具有多个元素的数组的真值不明确。请使用a.any()或a.all()”

解决方法

使用列表推导的方法应该可以解决问题。

def kiem_tra_so_hoan_chinh(so):
    if so <= 1:
        return False
    else:
        tong = 0
        for i in range(1,so):
            if so % i == 0:
                tong += i
        if tong == so:
            return True
        else:
            return False
    
np.random.seed(5)
arr1 = np.random.randint(low = 1,high = 101,size = 16) 
# use iterator to apply function to each element
is_perfect = np.array([kiem_tra_so_hoan_chinh(i) for i in arr1])
is_perfect_reshaped=is_perfect.reshape(4,4)
# each element is now a row of 4,so apply sum(row)>0 to find
# at least one perfect number.
contains_perfect = np.array([sum(row)>0 for row in is_perfect_reshaped])
print(arr1.reshape(4,4))
print(is_perfect_reshaped)
print(contains_perfect)

[[100  79  62  17]
 [ 74   9  63  28]
 [ 31  81   8  77]
 [ 16  54  81  28]]
[[False False False False]
 [False False False  True]
 [False False False False]
 [False False False  True]]
[False  True False  True]
,

方法1

np.vectorizeany用于列表理解。注意:np.vectorize只是个花哨的numpy for-loop

arr2 = arr1[[np.vectorize(kiem_tra_so_hoan_chinh)(i).any() for i in arr1],:]

Out[533]:
array([[74,9,63,28],[16,54,81,28]])

方法2:

np.vectorizenp.apply_along_axis

arr2 = arr1[np.apply_along_axis(np.vectorize(kiem_tra_so_hoan_chinh),1,arr1)
              .any(1),:]

Out[540]:
array([[74,28]])

方法3

np.frompyfunc,具有列表理解功能:

arr2 = arr1[[np.frompyfunc(kiem_tra_so_hoan_chinh,1)(i).any() for i in arr1],:]

Out[545]:
array([[74,28]])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。