【问题标题】:AttributeError: Python 'filter' object has no attribute 'sort'AttributeError:Python 'filter' 对象没有属性 'sort'
【发布时间】:2019-09-03 19:26:35
【问题描述】:

我遇到了问题

AttributeError: 'filter' 对象没有属性 'sort'

以下是整个错误信息:

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()

【问题讨论】:

  • filter 返回一个 filter 对象。如果你想要一个列表然后做fileList = list(filter(lambda x: '.mhd' in x, fileList))

标签: python-3.x sorting object filter


【解决方案1】:

在 python 3 中,过滤器返回可迭代。并且您在可迭代对象上调用 sort 方法,因此出现错误。 将可迭代对象包装在列表中

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

或者代替fileList.sort()在排序方法中传递可迭代

fileList= sorted(fileList)

Python 3 doc for filter

【讨论】:

    【解决方案2】:

    您正在使用 Python 3。过滤器返回一个可迭代的 filter 对象,但它没有 sort 方法。将过滤器对象包裹在list中。

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

    【讨论】:

      猜你喜欢
      • 2017-10-22
      • 2015-04-25
      • 1970-01-01
      • 2018-06-05
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多