2013-07-15 49 views
2

在归并计数倒位数代码:如何在Python中读取文件中的行并从中删除换行符?

count =0 
def merge(left,right): 
    """Assumes left and right are sorted lists. 
    Returns a new sorted list containing the same elements 
    as (left + right) would contain.""" 
    result = [] 
    global count 
    i,j = 0, 0 
    while i < len(left) and j < len(right): 
     if left[i] <= right[j]: 
      result.append(left[i]) 
      i = i + 1 
     else: 
      result.append(right[j]) 
      j = j + 1 
      count+=len(left[i:]) 
    while (i < len(left)): 
     result.append(left[i]) 
     i = i + 1 
    while (j < len(right)): 
     result.append(right[j]) 
     j = j + 1 
    return result 
def mergesort(L): 
    """Returns a new sorted list with the same elements as L""" 
    if len(L) < 2: 
     return L[:] 
    else: 
     middle = len(L)/2 
     left = mergesort(L[:middle]) 
     right = mergesort(L[middle:]) 
     together = merge(left,right) 
     return together 

a=[] 
inFile=open('a1.txt','r') 
for line in inFile: 
    fields=line.strip() 
    a.extend(fields) 
print mergesort(a) 
print count 

其中a1.txt包含:

46 
45 
44 
43 
42 

的文件中的整数中显示的列表应该是:

[42, 43, 44, 45, 46] 

但输出是作为

['2', '3', '4', '4', '4', '4', '4', '4', '5', '6'] 

为什么数字的数字和数字是分开的?

+0

检查此链接... http://stackoverflow.com/q/4791080/782145 –

+0

for循环利用.strip('\ n')或。strip('/ n')不记得那些是什么新行 –

+0

你的问题的标题与你陈述的问题有什么关系? – martineau

回答

4

你做错了两两件事:

  • 您没有将文本转换为整数
  • 您正在使用.extend()添加到列表中。

这两个错误共同使您的代码失败。

用途:

for line in inFile: 
    a.append(int(line)) 

代替。

Python字符串也是序列。使用a.extend()将输入序列的每个元素都添加到列表中;对于字符串,这意味着单个字符:

>>> a = [] 
>>> a.extend('foo') 
>>> a 
['f', 'o', 'o'] 

,另一方面list.append(),增加个人值列表:

>>> a = [] 
>>> a.append('foo') 
>>> a 
['foo'] 

int()是不是太挑剔的空白,所以即使你line值包括换行符,int(line)将工作:

>>> int('46\n') 
46 
1

您使用list.extend,extend接受一个迭代并迭代它,它逐字符地迭代字符串。

>>> a = [] 
>>> a.extend('123') 
>>> a 
['1', '2', '3'] 
>>> 

我想你想要的是list.append

0
with open('a1.txt') as f: 
    a = list(int(i) for i in f if i.strip()) 

print(a) 

最后一个if i.strip()是否有跳过空白行。

+2

也许'if i.strip()' –

1

append将一个元素添加到列表中,将第一个列表与另一个列表连接起来使用a.append(fields),它会正常工作。

相关问题