问题描述
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.vectorize
和any
用于列表理解。注意: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.vectorize
和np.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]])