简体   繁体   中英

Python list folders list by numeric order

I'm getting list of all the folders in specific directory with this code:

TWITTER_FOLDER = os.path.join('TwitterPhotos')
dirs = [d for d in os.listdir(TWITTER_FOLDER) if os.path.isdir(os.path.join(TWITTER_FOLDER, d))]

This is the array: ['1','2','3','4','5','6','7','8','9','10','11'] .

And I want to get the array in this order: ['11','10','9','8','7','6','5','4','3','2','1']

So I use this code for that:

dirs.sort(key=lambda f: int(filter(str.isdigit, f)))

and when I use it I get this error:

int() argument must be a string, a bytes-like object or a number, not 'filter'

Any idea what is the problem? Or how I can sort it in another way? It's important that the array will be sort by numeric order like:

12 11 10 9 8 7 6 5 4 3 2 1

And not:

9 8 7 6 5 4 3 2 12 11 1

Thanks!

Filter returns an iterator, you need to join them back into a string before you can convert it to an integer

dirs.sort(key=lambda f: int(''.join(filter(str.isdigit, f))))

Use sorted with key:

In [4]: sorted(f, key=lambda x: int(x), reverse=True)
Out[4]: ['11', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1']

Or you can do f.sort(key=lambda x:int(x), reverse=True) for inplace sort.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM