def insertionSort(a):
for i in range(1, len(a)): #outer loop covering the range
value = a[i] #value = to list, which will compare items to the left
i = i - 1 #i goes lower than index to compare further to the left
while i >= 0 : #keep comparing till its at the beginning of the list
if value < a[i]: #if value is less than i
a[i+1] = a[i] # shift number in right i to slot i + 1
a[i] = value # shift value that was left into slot i
i = i - 1
else:
break
infile = open("file1.txt", "r")
a=[]
for aline in infile:
a = aline.split()
insertionSort(a)
print(a)
这是文件中的内容:
7686850495948548545
如何让insertionSort()
函数处理文件?你知道吗
你的问题之一是你反复分配给
a
。那不是你想要的。现在,首先给a
分配一个空列表。然后,每次替换之前分配给a
的内容时,您都会将每一行分解分配给a
。我认为你真正想要的是:解决这个问题,然后让我们知道你的代码运行得有多好。你知道吗
这部分不太正确。你知道吗
打开和读取(或写入)文件的首选方式如下:
然后,一旦你把数字放在一个字符串中,你就可以把它们分成一个列表,如下所示:
所以
nums_list
现在是一个字符串列表,使用列表理解将它们转换为int:编辑:
只是为了好玩,这里有一个简明的版本:
.strip()
添加只是为了确保没有奇怪的空格转换。你知道吗相关问题 更多 >
编程相关推荐