AttributeError:Python“过滤器”对象没有属性“排序”

问题描述 投票:0回答:3

我有问题

AttributeError:“过滤器”对象没有属性“排序”

以下是完整的错误消息:

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()
python-3.x sorting object filter
3个回答
4
投票

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

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

或者代替

fileList.sort()
在排序方法中传递可迭代对象

fileList= sorted(fileList)

用于过滤器的Python 3 文档


0
投票

您使用的是 Python 3。 Filter 返回一个可迭代的

filter
对象,但它没有
sort
方法。 将滤镜对象包裹在
list
中。

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

0
投票

如果不想在过滤结果中引入额外的列表,可以使用 next() 来获取过滤器中的对象

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

这将根据 fileList 的类型返回 iter 或 None/[] 中的下一个对象。

© www.soinside.com 2019 - 2024. All rights reserved.