Pythonもいろいろできるのでいちいちメモしていてはきりがないのだが、

ちょっと便利だけどすぐ忘れそうなことをメモしておく。

 

例えば、次のような文字列のリスト dirlist があったとする。

ディレクトリのリストである。

 

>>> dirlist

['batch-sim_p1_l2', 'batch-sim_p1_l2-2', 'batch-sim_p1_l3
 'batch-sim_p1_l4', 'batch-sim_p2_l2', 'batch-sim_p2_l2-2
 'batch-sim_p2_l3', 'batch-sim_p2_l4', 'batch-sim_p3_l2',
 'batch-sim_p3_l2-2', 'batch-sim_p3_l3', 'batch-sim_p3_l4
 'batch-sim_t1_l2', 'batch-sim_t1_l2-2', 'batch-sim_t1_l3',
 'batch-sim_t1_l4', 'batch-sim_t2_l2', 'batch-sim_t2_l2-2',
 'batch-sim_t2_l3', 'batch-sim_t2_l4', 'batch-sim_t3_l2',
 'batch-sim_t3_l2-2', 'batch-sim_t3_l3', 'batch-sim_t3_l4'],

この各要素から batch-sim- を削除したいとする。

文字列の置換で

 

>>> [d.replace('batch-sim_','') for d in dirlist]

['p1_l2', 'p1_l2-2', 'p1_l3', 'p1_l4', 'p2_l2', 'p2_l2-2', 'p2_l3', 'p2_l4', 'p3_l2', 'p3_l2-2', 'p3_l3', 'p3_l4', 't1_l2', 't1_l2-2', 't1_l3', 't1_l4', 't2_l2', 't2_l2-2', 't2_l3', 't2_l4', 't3_l2', 't3_l2-2', 't3_l3', 't3_l4']

 

とすればよいが、batch-sim_ の部分が、実行時の引数として与えられるなど、

いつも同じではない場合、このように文字列をハードコードするとうまくいかない。

共通部分を自動的に検出したい。

 

そこで、os.path.commonprefix(list) が使える。

 

>>> from os import path

>>> path.commonprefix(dirlist)

'batch-sim_'

 

これを使うと、

 

>>> comstr = path.commonprefix(dirlist)

>>> [d.replace(comstr,'') for d in dirlist]

['p1_l2', 'p1_l2-2', 'p1_l3', 'p1_l4', 'p2_l2', 'p2_l2-2', 'p2_l3', 'p2_l4', 'p3_l2', 'p3_l2-2', 'p3_l3', 'p3_l4', 't1_l2', 't1_l2-2', 't1_l3', 't1_l4', 't2_l2', 't2_l2-2', 't2_l3', 't2_l4', 't3_l2', 't3_l2-2', 't3_l3', 't3_l4']

 

とできる。