2016-04-18 49 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

究竟不起作用?我已經可以看到兩個會導致腳本無法工作的錯誤 –

回答

0

你只是有一些語法錯誤:

  • 你應該聲明insertion_sort函數之前使用它
  • 您不能打印File類型,你應該做一個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

歡迎來到Stackoverflow!當給出一個答案時,最好給出[一些解釋,爲什麼你的答案](http://stackoverflow.com/help/how-to-answer)是一個。只有代碼答案可能最終被刪除。 –

相關問題