为什么循环中的数值没有附加到数组中?

huangapple go评论136阅读模式
英文:

Why aren't the values from the for loop appending to the array?

问题

  1. p = []
  2. for i in range(6):
  3. p.append(P(u[i]))
  4. p = np.array(p)
  5. print(p)
  6. 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.

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. j=np.array([14,15,16,16,16,22,22,24,24,25,25,25,25,25])
  4. u=np.unique(j)
  5. def P(age):
  6. sum=0
  7. for i in range(14):
  8. if j[i]==age:
  9. sum=sum+1
  10. else:
  11. sum=sum
  12. print(sum/14)
  13. p = []
  14. for i in range(6):
  15. p.append(P(u[i]))
  16. p=np.array(p)
  17. print(p)
  18. print(type(p))

Output:

  1. 0.07142857142857142
  2. 0.07142857142857142
  3. 0.21428571428571427
  4. 0.14285714285714285
  5. 0.14285714285714285
  6. 0.35714285714285715
  7. [None None None None None None]
  8. <class 'numpy.ndarray'>

答案1

得分: 0

  1. 函数 "P" 没有返回值因此每次返回 None
英文:

Function "P" doesn't have a return function, hence equaling None each time.

  1. def P(age):
  2. sum=0
  3. for i in range(14):
  4. if j[i]==age:
  5. sum=sum+1
  6. else:
  7. sum=sum
  8. print(sum/14)
  9. return sum/14

Shown here ^, you can return the sum.

答案2

得分: 0

因为您的函数 P() 没有 return 语句,即它返回 None

您可能想要更改此函数定义的最后一条语句,即语句

  1. print(sum/14)

  1. 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

  1. print(sum/14)

to

  1. return sum/14

(or append this return statement after your print(sum/14).)

huangapple
  • 本文由 发表于 2023年5月21日 07:11:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297672.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定