Help us understand the problem. What is going on with this article?

些細なこと:Pythonでファイルのソートを行う

問題

以下のファイルが存在し、これらを先頭の数で並び替えたい。

$ ls -1 *pdb
10_apo_1RTC_aln_void.pdb
10_hol_1BR6_aln_void.pdb
11_apo_1RDW_aln_void.pdb
.
.
.

まず、Pythonでこれらのファイル名をglobモジュールを使用してリストに格納してみるが、以下に示すように順番がバラバラである。

import glob
file_names = glob.glob("*.pdb")
file_name

出力

['14_hol_2HVD_aln_void.pdb',
 '31_apo_1QLW_aln_void.pdb',
 '27_apo_2BF3_aln_void.pdb',
 '67_hol_3CFN_aln_void.pdb',
 '23_hol_1IMB_aln_void.pdb',
 '61_apo_1K3F_aln_void.pdb',
 '34_apo_3DXN_aln_void.pdb',
 '34_hol_3HZT_aln_void.pdb',
 '24_apo_2AX9_aln_void.pdb',
 '49_hol_1S9D_aln_void.pdb',
 '60_apo_1PKL_aln_void.pdb',
.
.
.

方針

ソート関数とキーオプションを使う。

key = lambda var: int(var.split("_")[0])
sorted(file_names, key = key)

出力は以下のようになる

['1_hol_2IUZ_aln_void.pdb',
 '1_apo_3CHE_aln_void.pdb',
 '2_hol_1YV3_aln_void.pdb',
 '2_apo_2AKA_aln_void.pdb',
 '3_hol_2JDS_aln_void.pdb',
 '3_apo_2GFC_aln_void.pdb',
 '4_hol_1LIC_aln_void.pdb',
 '4_apo_1ALB_aln_void.pdb',
 '5_apo_1NEP_aln_void.pdb',
 '5_hol_2HKA_aln_void.pdb',

ちゃんと思ったとうりに並び替えることができた。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away