2016-02-27 139 views
0

我是Python的新手,我正在努力处理文件中的数字排序问题。我想做一个泡泡或插入排序,并按升序排列文件中的数字。数字不是整数。这是我到目前为止有:在Python中对文件进行排序

input_file=open("C:\\Users\\Rachel\\Documents\\Natural Sciences MSci\\Year 2\\Env Sci\\Comp Modelling\\Pptn data.txt", "r") 
header_line = input_file.readline() 
for line in input_file: 
print line 

list=input_file.read() 
print list 

def insertion_sort(items): 
for i in range(1, len(items)): 
    j=i 
    while j>0 and items[j] < items[j-1]: 
     temp=items[j] 
     items[j]=items[j-1] 
     items[j-1]=temp 
     j=j-1 

insertion_sort(list) 
print 'After sorting:', list 

我跑在此之后,未分类的列表打印和短语After sorting:显示,但没有数字的排序列表:d

我敢肯定,我错过了一些明显的东西,但我尝试过不同的方式,似乎无法得到它。

任何帮助将是伟大的 谢谢!

+0

另请注意,您可能希望使用file.readlines()而不是file.read()将文件的行读入列表中。 –

+0

你将不得不拆分'while j> 0和items [j] Elan

回答

0

对不起,你的目标是什么混淆。下面是正确的代码:

input_file=open("C:\\Users\\Rachel\\Documents\\Natural Sciences MSci\\Year 2\\Env Sci\\Comp Modelling\\Pptn data.txt", "r") 
header_line = input_file.readline() 

list=input_file.read().split() 


def insertion_sort(items): 
    for i in range(1, len(items)): 
     j = list[i] 
     i = i - 1 
     while i >= 0: 
      if j < list[i]: 
       list[i + 1] = list[i] 
       list[i] = j 
       i = i - 1 
      else: 
       break 


insertion_sort(list) 
print 'After sorting:', list 
1

的一个问题是,循环的初始输入文件耗尽了数据,因此,没有什么留在后续input_file.read()阅读。 read()也会返回一个字符串,而不是一个列表。但是无论如何,你的插入排序函数是在一个空字符串上运行的,所以它什么都不做。

您可以通过在for循环之后寻找文件的开头来解决第一个问题。第二个问题可以通过使用splitlines()通过分割线的输入是固定的:

header_line = next(input_file) 
for line in input_file: 
    print line 

input_file.seek(0) 
next(input-file) # skip header again 
list=input_file.read().splitlines() 
print list 

但它可能是更好的只是这样做:

with open('input_file') as input_file: 
    header_line = next(input_file).strip() 
    numbers = [line.strip() for line in input_file] 
    # if you really want to print them out first... 
    for number in numbers: 
     print number 

    insertion_sort(numbers) 

注:此代码不会将文件中的数据转换为任何数字类型(例如整数),因为您说数字不是整数......所以它们是什么?不转换为数字类型意味着您的排序函数将根据数字字符串的ASCII排序顺序进行排序,因此'10'将在'2'之前排序。

如果数字可以浮动,就可以读取文件时,做到这一点:

numbers = [float(line) for line in input_file] 

现在您的排序功能的数字,如1或1.0作为花车排序。

0

你的算法似乎工作得很好。我在我的电脑上尝试了以下内容。 我创建了一个名为numbers.txt文件,并放在数字以下列方式:

23 
23.4 
4 
5 
6.7 
1 
0 
6 
34 

然后运行以下代码:

def insertion_sort(items): 
    for i in range(1, len(items)): 
     j = i 
     while j > 0 and items[j] < items[j-1]: 
      temp = items[j] 
      items[j] = items[j - 1] 
      items[j - 1] = temp 
      j = j - 1 

numbers = open("numbers.txt").read().split() 
numbers = [float(number) for number in numbers] 
print "Before sorting: ", numbers 
insertion_sort(numbers) 
print "After sorting: ", numbers 

这给了我下面的输出:

Before sorting: [23.0, 23.4, 4.0, 5.0, 6.7, 1.0, 0.0, 6.0, 34.0] 
After sorting: [0.0, 1.0, 4.0, 5.0, 6.0, 6.7, 23.0, 23.4, 34.0] 

我希望这会有所帮助。

+0

问题不在于排序算法,它是在读取文件的代码中。 – mhawke

+0

@mhawke是的,正是我的观点。 –

+0

@mhawke哦,我没有意识到你已经发布了相同的内容。没有刷新页面。对于那个很抱歉。 –

相关问题