2016-04-18 29 views
0

pythonを使ってファイルから昇順にソートする簡単な方法を見つけようとしています。Pythonでファイル内の昇順でソートする方法(挿入ソートによる)

これは私が今までに得たものですが、うまくいかないようです。

input_file = open('C:\\Users|\Desktop\\data.txt') 
for line in input_file: 
    print line 

print('Before: ', input_file) 
insertion_sort(input_file) 
print('After : ', input_file) 
def insertion_sort(items): 
    """ Implementation of insertion sort """ 
    for i in range(1, len(items)): 
     j = i 
     while j > 0 and items[j] < items[j-1]: 
      items[j], items[j-1] = items[j-1], items[j] 
      j -= 1 

ご協力いただければ幸いです。

+1

正確に何をして動作しませんか?私はすでにこのスクリプトが動作しないようになる2つのエラーを見ることができます –

答えて

0

あなただけのいくつかの文法エラーがあります。そして、あなたはFileタイプを印刷することはできません

  • insertion_sort機能は、前のファイルの内容を読み取るために、あなたはListを作る必要があり、それを使用して宣言する必要があり

    • をソートList/を使用し、Listを返し、List
    • ファイル名は多分間違って印刷するには、Windows
    • で優れています

    これを試してみてください:

    input_file = open('C:/Users/Desktop/data.txt') 
    
    lst = [] 
    for line in input_file: 
        lst.append(int(line.strip())) 
    
    def insertion_sort(items): 
        """ Implementation of insertion sort """ 
        for i in range(1, len(items)): 
         j = i 
         while j > 0 and items[j] < items[j - 1]: 
          items[j], items[j - 1] = items[j - 1], items[j] 
          j -= 1 
        return items 
    
    print('Before: ', lst) 
    print('After : ', insertion_sort(lst)) 
    
  • +0

    ようこそ!答えを与えるときは、[あなたの答えが何であるかについてのいくつかの説明](http://stackoverflow.com/help/how-to-answer)を与えることが望ましいです。コードのみの回答が削除される可能性があります。 –

    関連する問題