[英]Python - Casting a float as int to be used as array index returns 0th element of the array
I want to create a new array that has some sifted elements from an old array我想创建一个新数组,其中包含旧数组中的一些筛选元素
This is what the array looks like:这是数组的样子:
print(freqs[0])
print(freqs[1])
print(freqs[2])
print(freqs[3])
print(freqs[4])
>>(-1.356524149576826+0j)
(-1.5188337718697111-0.0028277787696928914j)
(-1.537925820349816+0.02545857328595845j)
(-1.7483732926022144+0.0875845050778933j)
(-1.8506826888571075+0.16201185108446528j)
when I cast the index "manually" to troubleshoot it all works fine当我“手动”投射索引以进行故障排除时,一切正常
print(int(0*scaler), freqs[int(0*scaler)])
print(int(1*scaler), freqs[int(1*scaler)])
print(int(2*scaler), freqs[int(2*scaler)])
print(int(3*scaler), freqs[int(3*scaler)])
print(int(4*scaler), freqs[int(4*scaler)])
>>0 (-1.356524149576826+0j)
0 (-1.356524149576826+0j)
1 (-1.5188337718697111-0.0028277787696928914j)
2 (-1.537925820349816+0.02545857328595845j)
3 (-1.7483732926022144+0.0875845050778933j)
However, once I put this kind of logic in a loop I always get the 0th element.但是,一旦我将这种逻辑放入循环中,我总是会得到第 0 个元素。 And I doubled checked that my index variable is in fact an int我加倍检查我的索引变量实际上是一个 int
for i in range(length):
index = int(i*scaler)
if index < length:
newfreqs[i] = freqs[index]
print(i,index,freqs[index])
>>0 0 (-1.356524149576826+0j)
1 0 (-1.356524149576826+0j)
2 1 (-1.356524149576826+0j)
3 2 (-1.356524149576826+0j)
4 3 (-1.356524149576826+0j)
I get the exact same behavior if I use math.floor() instead of int().如果我使用 math.floor() 而不是 int(),我会得到完全相同的行为。 Oddly round() seems to work fine but it does not produce the correct index value I need.奇怪的是 round() 似乎工作正常,但它不会产生我需要的正确索引值。 It is only an issue anywhere inside the loop, outside the loop it works as expected.这只是循环内任何地方的问题,循环外它按预期工作。
Here is the entire function这是整个 function
def reindex(freqs, halfSteps):
scaler = halfStep**(-halfSteps)
newfreqs = freqs
length = len(newfreqs)
for i in range(length):
index = int(i*scaler)
if index < length:
newfreqs[i] = freqs[index]
print(i,index,freqs[index])
return newfreqs
Changed the initialization of newfreq to 'zeros(len(freqs))'将 newfreq 的初始化更改为 'zeros(len(freqs))'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.