首页 > 解决方案 > 我的函数的哪一部分导致 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

为什么我会收到此错误?我该如何解决?

编辑以添加功能说明: 在此处输入图像描述

标签: pythonloopstypeerror

解决方案


这是他们试图让您编写的代码。

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

推荐阅读