2013-07-15 43 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),它會正常工作。

相關問題