在歸併計數倒位數代碼:如何在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']
爲什麼數字的數字和數字是分開的?
檢查此鏈接... http://stackoverflow.com/q/4791080/782145 –
for循環利用.strip('\ n')或。strip('/ n')不記得那些是什麼新行 –
你的問題的標題與你陳述的問題有什麼關係? – martineau