python - 我的函数的哪一部分导致 TypeError:列表索引必须是整数或切片,而不是浮点数?
问题描述
我正在为分配创建一个 median_filter 函数。这是我的代码:
def median_filter(y, W):
""" (list, int) -> list
Returns a list whose ith item is
the median value of y[start:stop+1] where
start is the larger of 0 and i - W and
stop is the smaller of i + W and n-1.
>>> median_filter([-1.0, 6.0, 7.0, -2.0, 0.0, 8.0, 13.0], 1)
[2.5, 6.0, 6.0, 0.0, 0.0, 8.0, 10.5]
"""
for i, element in enumerate(y):
ynew = []
if i-W >= 0 and i+W < len(y):
ynew.append([my_median([y[i-W],y[int(i)], y[i+W]]) for i in y])
if i-W < 0 and i+W < len(y):
ynew.append([my_median([y[0], y[1]]) for i in y])
if i-W >= 0 and i+W >= len(y):
ynew.append([my_median([y[len(y)-2], y[len(y)-1]]) for i in y])
i+=1
return ynew
它给出了这个错误:
Traceback (most recent call last):
File "C:\Users\*****\Desktop\****\", line 339, in <listcomp>
ynew.append([my_median([y[i-W],y[int(i)], y[i+W]]) for i in y])
TypeError: list indices must be integers or slices, not float
为什么我会收到此错误?我该如何解决?
解决方案
这是他们试图让您编写的代码。
def median_filter(y, W):
""" (list, int) -> list
Returns a list whose ith item is
the median value of y[start:stop+1] where
start is the larger of 0 and i - W and
stop is the smaller of i + W and n-1.
>>> median_filter([-1.0, 6.0, 7.0, -2.0, 0.0, 8.0, 13.0], 1)
[2.5, 6.0, 6.0, 0.0, 0.0, 8.0, 10.5]
"""
ynew = []
for i in range(len(y)):
if i-W >= 0 and i+W < len(y):
val = my_median( y[i-W:i+W+1] )
elif i-W < 0 and i+W < len(y):
val = my_median( y[0:y[i+W+1] )
elif i-W >= 0 and i+W >= len(y):
val = my_median( y[i-W:] )
ynew.append( val )
return ynew
更简单的是:
ynew = []
for i in range(len(y)):
ynew.append( my_median( y[max(0,i-W):min(i+W+1,len(y))] ) )
return ynew
推荐阅读
- vb.net - 公共函数返回 VB.Net
- python - 带复位的累积和
- android - 为什么在使用“flutter build aar”命令制作 aar 时,Android 项目中无法访问 dart 类?
- javascript - 设置 favicon 时不出现 React-FontAwesome 图标
- r - 用 survfit() 拟合生存曲线
- wpf - 您将如何在 WPF 中构建移动样式的 Shift 键?
- angular - 如何在单击反应形式的提交按钮时重置所有验证
- perl - 带有 U 选项和大写选项字符的音译
- visual-studio-code - 在 VS Code 中,如何对接 Webview 开发者工具?
- javascript - TypeError:无法读取未定义的属性“事件”