对从文件中读取的列表进行排序?

时间:2016-04-27 18:48:21

标签: python

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()函数处理文件?

2 个答案:

答案 0 :(得分: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()只是为了确保没有奇怪的空格。

答案 1 :(得分:0)

您的一个问题是您反复分配给a。那不是你想要的。现在,您首先为a分配一个空列表。然后,每次更换先前分配给a的内容时,将每行分解为a。我认为你在for循环中真正想要的是:

a.extend(aline.split())

修复此问题,然后告诉我们您的代码运行情况。