Reputation: 7900
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!
Upvotes: 0
Views: 295
Reputation: 43300
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))))
Upvotes: 2
Reputation: 2882
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.
Upvotes: 2