用于计算mergesort中的反转次数的代码:
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 :(得分: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 :(得分:1)
你使用list.extend
,extend
接受一个iterable并迭代它,它逐个字母地迭代字符串。
>>> a = []
>>> a.extend('123')
>>> a
['1', '2', '3']
>>>
我认为你想要的是list.append
。
答案 2 :(得分:1)
append将一个元素添加到列表中,extend将第一个列表与另一个列表连接起来 使用a.append(字段),它会正常工作。
答案 3 :(得分:0)
with open('a1.txt') as f:
a = list(int(i) for i in f if i.strip())
print(a)
最后if i.strip()
是跳过空行。