pythonpython-3.xsortingfilter

AttributeError: Python 'filter' object has no attribute 'sort'


I am having issues with

AttributeError: 'filter' object has no attribute 'sort'

Below is the whole error message:

Using TensorFlow backend.
Traceback (most recent call last):
  File "D:/Data/PROMISE2012/Vnet3d_data/promise12_Unet_segmentation-master/promise12_segmentation-master/codes/train.py", line 231, in <module>
    n_imgs=15*10**4, batch_size=32)
  File "D:/Data/PROMISE2012/Vnet3d_data/promise12_Unet_segmentation-master/promise12_segmentation-master/codes/train.py", line 166, in keras_fit_generator
    data_to_array(img_rows, img_cols)
  File "D:/Data/PROMISE2012/Vnet3d_data/promise12_Unet_segmentation-master/promise12_segmentation-master/codes/train.py", line 48, in data_to_array
    fileList.sort()
AttributeError: 'filter' object has no attribute 'sort'

Process finished with exit code 1
def data_to_array(img_rows, img_cols):
    clahe = cv2.createCLAHE(clipLimit=0.05, tileGridSize=(int(img_rows/8),int(img_cols/8)) )

    fileList =  os.listdir('TrainingData/')
    fileList = filter(lambda x: '.mhd' in x, fileList)
    fileList.sort()

Solution

  • In python 3, filter returns iterator. and you are calling sort method on iterator hence getting an error. Either wrap iterator in list

    fileList = list(filter(lambda x: '.mhd' in x, fileList))
    

    or instead of fileList.sort() pass iterator to sorted function

    fileList = sorted(fileList)
    

    Python 3 doc for filter