python - 如何使用for循环重新分配数组中的元素 [英] python - how to reassign element in array with for loop
问题描述
我有一个 numpy 浮点数组,我想使用 for 循环用不同的值重新分配它,但 PyCharm 说没有使用新的变量分配.
I have a numpy array of floats that I want to reassign with a different value using a for loop but PyCharm says the new variable assignment isn't being used.
如果我有,请说:
for i in array:
i = i * 5
它会说 i 是一个未使用的变量.我做错了什么?
It will say that i is an unused variable. What am I doing wrong?
推荐答案
您需要为数组元素赋值.否则你的数组将保持不变.有几种方法.
You need to assign values to array elements. Otherwise you array will remain unchanged. There are a couple of ways.
以您当前的尝试为起点,您可以使用 enumerate
.给定一个输入 array
:
Using your current attempt as a starting point, you can use enumerate
. Given an input array
:
for idx, val in enumerate(array):
array[idx] = val * 5
但这并没有利用 NumPy 矢量化.您可以简单地使用:
But this doesn't take advantage of NumPy vectorisation. You can simply use:
array *= 5
这篇关于python - 如何使用for循环重新分配数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!