英文:
Why aren't the values from the for loop appending to the array?
问题
p = []
for i in range(6):
p.append(P(u[i]))
p = np.array(p)
print(p)
print(type(p))
英文:
I'm trying to append values from a for loop into a numpy array. While the values are correct, the array only returns none values. The values entered are from another numpy array.
import numpy as np
import matplotlib.pyplot as plt
j=np.array([14,15,16,16,16,22,22,24,24,25,25,25,25,25])
u=np.unique(j)
def P(age):
sum=0
for i in range(14):
if j[i]==age:
sum=sum+1
else:
sum=sum
print(sum/14)
p = []
for i in range(6):
p.append(P(u[i]))
p=np.array(p)
print(p)
print(type(p))
Output:
0.07142857142857142
0.07142857142857142
0.21428571428571427
0.14285714285714285
0.14285714285714285
0.35714285714285715
[None None None None None None]
<class 'numpy.ndarray'>
答案1
得分: 0
函数 "P" 没有返回值,因此每次返回 None。
英文:
Function "P" doesn't have a return function, hence equaling None each time.
def P(age):
sum=0
for i in range(14):
if j[i]==age:
sum=sum+1
else:
sum=sum
print(sum/14)
return sum/14
Shown here ^, you can return the sum.
答案2
得分: 0
因为您的函数 P()
没有 return
语句,即它返回 None
。
您可能想要更改此函数定义的最后一条语句,即语句
print(sum/14)
为
return sum/14
(或在 print(sum/14)
后追加此 return
语句)。
英文:
Because your function P()
has no return
statement, i.e. it returns None
.
You probably want to change the last statement of this function definition, i.e. the statement
print(sum/14)
to
return sum/14
(or append this return
statement after your print(sum/14)
.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论