Jim
Jim

Reputation: 83

modify the following with function lambda and filter python2 code into python 3

I need to convert the following python2.7 code into python3.5, while getting errors

 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'

Upvotes: 2

Views: 379

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140316

In Python 2, when passed a string in input, filter used to return a string, which was convenient.

Now filter returns a filter object, which needs to be iterated upon to get the results.

So you have to use "".join() on the result to force iteration & convert to string.

Also note that lambda x: x.isdigit() is overkill and underperformant, use str.isdigit directly.

Another potential bug in your code is that f is the full path name of the file, so if there are digits in the paths, they'll be taken into account (and would be difficult to figure out), so a proper fix would be:

int("".join(filter(str.isdigit, os.path.basename(f))))

Upvotes: 2

Related Questions