Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control order of result from iterator in python

I use pathlib.Path().iterdir() to get sub-dictionary of the path.

Under /home/yuanyi/workspace/app, there are 4 folders: 01, 02, 03, 04.

from pathlib import Path
for subdir in Path('/home/yuanyi/workspace/app').iterdir():
    print(subdir)

But the result is not ordered.

/home/yuanyi/workspace/app/02
/home/yuanyi/workspace/app/03
/home/yuanyi/workspace/app/01
/home/yuanyi/workspace/app/00

Wht the result is not the following:

/home/yuanyi/workspace/app/01
/home/yuanyi/workspace/app/02
/home/yuanyi/workspace/app/03
/home/yuanyi/workspace/app/04

I want to know how the iterator works, and what's the best method to get ordered result.

like image 635
wuyuanyi Avatar asked Mar 16 '16 11:03

wuyuanyi


2 Answers

You can use "sorted()"

Built-in Functions Python - sorted()

from pathlib import Path
for subdir in sorted(Path('/some/path').iterdir()):
    print(subdir)

NOTE: @NamitJuneja points out, This changes iterating over a generator to iterating over a list. Hence if there are a huge number of files in the memory, loading them all into the memory (by loading them into a list) might cause problems.

On my Mac, the iterdir() method returns the list already sorted. So that looks system dependent. What OS are you using?

like image 162
Tim Grant Avatar answered Oct 16 '22 10:10

Tim Grant


Think you should figure out the result from this,

>>> l = ['/home/yuanyi/workspace/app/02',
'/home/yuanyi/workspace/app/03', '/home/yuanyi/workspace/app/01']
>>> for i in sorted(l, key=lambda m: int(m.split('/')[-1])):
    print i


/home/yuanyi/workspace/app/01
/home/yuanyi/workspace/app/02
/home/yuanyi/workspace/app/03
>>> 

or

for i in sorted(l, key=lambda m: int(m.split(os.sep)[-1])):
    print i
like image 3
Avinash Raj Avatar answered Oct 16 '22 10:10

Avinash Raj