我需要将以下python2.7代码转换为python3.5,同时获得错误
for filename in sorted(glob.glob(self.path + '/test*.bmp'),
key=lambda f: int(filter(lambda x: x.isdigit(), f))):
Error:
Traceback (most recent call last):
File "/Users/ImageSegmentation/preprocess.py", line 53, in get_gland
key=lambda f: int((filter(lambda x: x.isdigit(), f)))):
File "/Users/ImageSegmentation/preprocess.py", line 53, in <lambda>
key=lambda f: int((filter(lambda x: x.isdigit(), f)))):
TypeError: int() argument must be a string, a bytes-like object or a number, not 'filter'发布于 2017-12-08 15:32:51
在Python2中,当在输入中传递一个字符串时,filter用来返回一个字符串,这很方便。
现在,filter返回一个filter对象,需要对该对象进行迭代才能获得结果。
因此,您必须对结果使用"".join()来强制迭代&将其转换为字符串。
还请注意,lambda x: x.isdigit()是过分的和不合格的,直接使用str.isdigit。
代码中另一个潜在的错误是,f是文件的完整路径名,因此如果路径中有数字,就会考虑到它们(并且很难确定),所以正确的修复方法是:
int("".join(filter(str.isdigit, os.path.basename(f))))https://stackoverflow.com/questions/47717337
复制相似问题