0

我试图找出一种简单的方法来使用 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

任何帮助将不胜感激!!

4

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))
于 2017-02-15T03:28:57.133 回答