2016-04-27 68 views
-2
def insertionSort(a): 
    for i in range(1, len(a)): #outer loop covering the range 
     value = a[i] #value = to list, which will compare items to the left 
     i = i - 1 #i goes lower than index to compare further to the left 
     while i >= 0 : #keep comparing till its at the beginning of the list 
      if value < a[i]: #if value is less than i 
       a[i+1] = a[i] # shift number in right i to slot i + 1 
       a[i] = value # shift value that was left into slot i 
       i = i - 1 
      else: 
       break 

infile = open("file1.txt", "r") 
a=[] 
for aline in infile: 
    a = aline.split() 

insertionSort(a) 
print(a) 

這是什麼文件:對從文件中讀取的列表進行排序?

7686850495948548545 

如何獲得insertionSort()功能對文件的工作?

+0

該文件是否包含一行中的所有數字? – trans1st0r

+1

當您執行'a = aline.split()'時,它不會在變量'a'之外保留一個引用,因此for循環中的下一個迭代將用下一行覆蓋它,所以最終發生的是您只調用排序在**文件的最後一行** –

+0

如果您改爲使用'a.extend(aline.split())',那麼您將擴展該列表中所有單詞(或數字)的列表,並最終以全部他們在for循環之後。 –

回答

2

這部分不完全正確。

infile = open("file1.txt", "r") 
a=[] 
for aline in infile: 
    a = aline.split() 

打開和讀取(或寫入)的文件的首選方法是:

with open('some_file.txt', 'r') as in_file: 
    string_numbers = in_file.read() 

然後,一旦你在一個字符串有數字,你可以把它們分成像列表所以:

nums_list = list(string_nums) 

所以nums_list現在是字符串列表,將其轉換爲整數與列表理解:

nums = [int(num) for num in nums_list] 

編輯:

只是爲了好玩,這裏的簡潔版本:

with open('filename.txt') as in_file: 
    nums = [int(n) for n in list(in_file.read().strip())] 

.strip()僅增加了,以確保沒有奇怪的空白鑄造。

+0

'string_nums.split()'不會做你的想法。在Python控制檯中查看''7686850495948548545'.split()'的結果。 – martineau

+0

你絕對正確,我的意思是list(string_nums)'。謝謝,編輯。 – Will

+0

謝謝! :+) –

0

你的問題之一是你一再分配到a。這不是你想要的。現在你開始分配一個空列表a。然後,將每條線分解爲a,每次替換之前分配給a的內容。我認爲你在for循環中實際需要的是:

a.extend(aline.split()) 

修復並讓我們知道你的代碼運行得如何。