1

だから私はファイル(数千行)input.txtに次の出力を持っています

2956:1 1076:1 4118:1 1378:1 2561:1 
1039:1 1662:1
1948:1 894:1 1797:1 1662:1

問題は、各行を昇順でソートする必要があることです

望ましい出力: output.txt

1076:1 1378:1 2561:1 2956:1 4118:1
1039:1 1662:1
894:1 1662:1 1797:1 1948:1

これは、私のためにこれを行うためのpython関数を探しています。行は順番どおりに並べる必要がありますが、各行は (出力と同様に) 昇順で並べ替える必要があります。

これを行う方法についてのアイデアはありますか?

4

3 に答える 3

11
with open('input.txt') as f, open('output.txt', 'w') as out:
    for line in f:
        line = line.split()  #splits the line on whitespaces and returns a list
        #sort the list based on the integer value of the item on the left side of the `:`
        line.sort(key = lambda x: int(x.split(':')[0]))
        out.write(" ".join(line) + '\n')

出力:

1076:1 1378:1 2561:1 2956:1 4118:1
1039:1 1662:1
894:1 1662:1 1797:1 1948:1
于 2013-06-04T13:40:52.180 に答える
2

Pythonについてはわかりませんが、一般的には、各行を「レコード」として取り、その行をスペースで区切られた配列に「分解」します(または、スペースまたはタブのグループを正規表現するか、セパレーターは何でも)、次に、単純な配列の並べ替えを行い、文字列に「内破」します。

私の「引用符」は PHP 関数と同等です。

于 2013-06-04T13:41:09.477 に答える
1

それを行う1つの方法は次のとおりです。

def sort_input(input_file):
  for line in input_file:
    nums = line.strip().split()
    nums.sort(key=lambda x: int(x.split(':')[0]))
    print ' '.join(nums)
于 2013-06-04T13:47:16.187 に答える