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()
功能對文件的工作?
該文件是否包含一行中的所有數字? – trans1st0r
當您執行'a = aline.split()'時,它不會在變量'a'之外保留一個引用,因此for循環中的下一個迭代將用下一行覆蓋它,所以最終發生的是您只調用排序在**文件的最後一行** –
如果您改爲使用'a.extend(aline.split())',那麼您將擴展該列表中所有單詞(或數字)的列表,並最終以全部他們在for循環之後。 –