2016-04-18 43 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)是一个。只有代码答案可能最终被删除。 –

相关问题