2016-02-27 142 views
0

我是Python的新手,我正在努力處理文件中的數字排序問題。我想做一個泡泡或插入排序,並按升序排列文件中的數字。數字不是整數。這是我到目前爲止有:在Python中對文件進行排序

input_file=open("C:\\Users\\Rachel\\Documents\\Natural Sciences MSci\\Year 2\\Env Sci\\Comp Modelling\\Pptn data.txt", "r") 
header_line = input_file.readline() 
for line in input_file: 
print line 

list=input_file.read() 
print list 

def insertion_sort(items): 
for i in range(1, len(items)): 
    j=i 
    while j>0 and items[j] < items[j-1]: 
     temp=items[j] 
     items[j]=items[j-1] 
     items[j-1]=temp 
     j=j-1 

insertion_sort(list) 
print 'After sorting:', list 

我跑在此之後,未分類的列表打印和短語After sorting:顯示,但沒有數字的排序列表:d

我敢肯定,我錯過了一些明顯的東西,但我嘗試過不同的方式,似乎無法得到它。

任何幫助將是偉大的 謝謝!

+0

另請注意,您可能希望使用file.readlines()而不是file.read()將文件的行讀入列表中。 –

+0

你將不得不拆分'while j> 0和items [j] Elan

回答

0

對不起,你的目標是什麼混淆。下面是正確的代碼:

input_file=open("C:\\Users\\Rachel\\Documents\\Natural Sciences MSci\\Year 2\\Env Sci\\Comp Modelling\\Pptn data.txt", "r") 
header_line = input_file.readline() 

list=input_file.read().split() 


def insertion_sort(items): 
    for i in range(1, len(items)): 
     j = list[i] 
     i = i - 1 
     while i >= 0: 
      if j < list[i]: 
       list[i + 1] = list[i] 
       list[i] = j 
       i = i - 1 
      else: 
       break 


insertion_sort(list) 
print 'After sorting:', list 
1

的一個問題是,循環的初始輸入文件耗盡了數據,因此,沒有什麼留在後續input_file.read()閱讀。 read()也會返回一個字符串,而不是一個列表。但是無論如何,你的插入排序函數是在一個空字符串上運行的,所以它什麼都不做。

您可以通過在for循環之後尋找文件的開頭來解決第一個問題。第二個問題可以通過使用splitlines()通過分割線的輸入是固定的:

header_line = next(input_file) 
for line in input_file: 
    print line 

input_file.seek(0) 
next(input-file) # skip header again 
list=input_file.read().splitlines() 
print list 

但它可能是更好的只是這樣做:

with open('input_file') as input_file: 
    header_line = next(input_file).strip() 
    numbers = [line.strip() for line in input_file] 
    # if you really want to print them out first... 
    for number in numbers: 
     print number 

    insertion_sort(numbers) 

注:此代碼不會將文件中的數據轉換爲任何數字類型(例如整數),因爲您說數字不是整數......所以它們是什麼?不轉換爲數字類型意味着您的排序函數將根據數字字符串的ASCII排序順序進行排序,因此'10'將在'2'之前排序。

如果數字可以浮動,就可以讀取文件時,做到這一點:

numbers = [float(line) for line in input_file] 

現在您的排序功能的數字,如1或1.0作爲花車排序。

0

你的算法似乎工作得很好。我在我的電腦上嘗試了以下內容。 我創建了一個名爲numbers.txt文件,並放在數字以下列方式:

23 
23.4 
4 
5 
6.7 
1 
0 
6 
34 

然後運行以下代碼:

def insertion_sort(items): 
    for i in range(1, len(items)): 
     j = i 
     while j > 0 and items[j] < items[j-1]: 
      temp = items[j] 
      items[j] = items[j - 1] 
      items[j - 1] = temp 
      j = j - 1 

numbers = open("numbers.txt").read().split() 
numbers = [float(number) for number in numbers] 
print "Before sorting: ", numbers 
insertion_sort(numbers) 
print "After sorting: ", numbers 

這給了我下面的輸出:

Before sorting: [23.0, 23.4, 4.0, 5.0, 6.7, 1.0, 0.0, 6.0, 34.0] 
After sorting: [0.0, 1.0, 4.0, 5.0, 6.0, 6.7, 23.0, 23.4, 34.0] 

我希望這會有所幫助。

+0

問題不在於排序算法,它是在讀取文件的代碼中。 – mhawke

+0

@mhawke是的,正是我的觀點。 –

+0

@mhawke哦,我沒有意識到你已經發布了相同的內容。沒有刷新頁面。對於那個很抱歉。 –

相關問題