gpt4 book ai didi

python - 在这种情况下有更好的方法使用 numpy 吗?

转载 作者:行者123 更新时间:2023-12-02 01:26:18 24 4
gpt4 key购买 nike

我的输出看起来像这样,但我的代码不是不好的做法吗?有没有办法用 numpy 函数替换 for ?

[[ 1.   1.5  2.   2.5  3. ]
[ 3.5 4. 4.5 5. 5.5]
[ 6. 6.5 7. 7.5 8. ]
[ 8.5 9. 9.5 10. 10.5]
[11. 11.5 12. 12.5 13. ]
[13.5 14. 14.5 15. 15.5]
[16. 16.5 17. 17.5 18. ]
[18.5 19. 19.5 20. 20.5]]
import numpy as np

list = []
x = 0.5

for i in range(8):
temp = []
list.append(temp)
for j in range(5):
x += 0.5
temp.append(x)


array = np.array(list)

最佳答案

您不应该在 numpy 中使用循环,而应该使用矢量代码。

您似乎想要 numpy.arangereshape 结合:

n, m = 8, 5
start = 0.5
step = 0.5

out = np.arange(start+step, start+step*(n*m+1), step).reshape(n, m)

输出:

array([[ 1. ,  1.5,  2. ,  2.5,  3. ],
[ 3.5, 4. , 4.5, 5. , 5.5],
[ 6. , 6.5, 7. , 7.5, 8. ],
[ 8.5, 9. , 9.5, 10. , 10.5],
[11. , 11.5, 12. , 12.5, 13. ],
[13.5, 14. , 14.5, 15. , 15.5],
[16. , 16.5, 17. , 17.5, 18. ],
[18.5, 19. , 19.5, 20. , 20.5]])

关于python - 在这种情况下有更好的方法使用 numpy 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74531286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com