Python 3.x 使用lambda函数修改以下内容,并将python2代码过滤到pytho3中
我需要将下面的python2.7代码转换为python3.5,同时会出现错误Python 3.x 使用lambda函数修改以下内容,并将python2代码过滤到pytho3中,python-3.x,python-2.7,lambda,filter,Python 3.x,Python 2.7,Lambda,Filter,我需要将下面的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/ImageSe
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'
用于排序后的文件名(glob.glob(self.path+'/test*.bmp'),
key=lambda f:int(过滤器(lambda x:x.isdigit(),f)):
错误:
回溯(最近一次呼叫最后一次):
文件“/Users/ImageSegmentation/preprocess.py”,第53行,在get_中
key=lambda f:int((过滤器(lambda x:x.isdigit(),f))):
文件“/Users/ImageSegmentation/preprocess.py”,第53行,在
key=lambda f:int((过滤器(lambda x:x.isdigit(),f))):
TypeError:int()参数必须是字符串、类似于对象的字节或数字,而不是“筛选器”
在Python 2中,当在输入中传递字符串时,过滤器用于返回字符串,这很方便
现在filter
返回一个filter对象,需要对其进行迭代才能得到结果
因此,必须对结果使用“”.join()
,以强制迭代并转换为字符串
还要注意的是,lambda x:x.isdigit()
的杀伤力过大且表现不佳,请直接使用str.isdigit
代码中的另一个潜在错误是f
是文件的完整路径名,因此如果路径中有数字,则会考虑这些数字(并且很难计算),因此正确的修复方法是:
int("".join(filter(str.isdigit, os.path.basename(f))))
…您确定这在Python 2中有效吗?它似乎会得到相同的错误,但是使用'list'
而不是'filter'
@glibdud no,因为filter用于在传递字符串时返回字符串。这是一个很好的特征,现在消失了…@Jean-Françoisfare啊,我明白了,这是一根线。谢谢