它在很大程度上是有效的,但输出看起来像地狱一样凌乱,所以我如何才能清理它,如果可能的话,我还想知道如何表达伪代码。
#open file with list
infile = open("unsorted_fruits.txt", "r")
#open file writing to
outfile = open("sorted_fruits.txt", "w")
#create variable to work with list
all_lines = infile.readlines()
for line in all_lines:
print (line,)
#this function has sorted other list
def insertion_sort(list):
for index in range(1, len(list)):
value = list[index]
i = index - 1
while i >= 0:
if value < list[i]:
list[i+1] = list[i]
list[i] = value
i = i - 1
else:
break
#calling the function to sort
insertion_sort(all_lines)
all_sorted = str(all_lines)
#print list to show its sorted
print (all_sorted)
#write the sorted list to the file
outfile.write(all_sorted)
infile.close()
outfile.close()
exit() 输入:木瓜
猕猴桃
zapote blanco
哈克贝利
香蕉
图2
酸橙
西瓜
香草
yiessas
罗望子
umkolo
昆斯
苹果
imbu
接骨木
杨梅
芒果
草莓
油桃
日期
樱桃
桔黄色的
西瓜
葡萄
树莓
输出:'\n','\n','\n','\n','apple\n','banana\n','cherry\n','date\n','elderberry\n','fig\n','grape\n','huckleberry\n','imbu\n','juneberry\n',‘奇异果\n’,‘酸橙\n’,‘芒果\n’,‘油桃\n’,‘橙色\n’,‘木瓜\n’,‘木瓜\n’,‘覆盆子\n’,‘草莓\n’,‘罗望子\n’,'umkolo\n',‘香草\n’,‘西瓜\n’,'xigua\n','yiessas\n','zapote blanco\n‘
发布于 2017-10-26 10:34:35
现在,使用以下代码的输出文件如下所示。任何人都有让它看起来更好的建议。blanco'\n','\n','\n','\n','apple\n','banana\n','cherry\n','date\n','elderberry\n','fig\n','grape\n','huckleberry\n','imbu\n','juneberry\n',‘奇异果\n’,‘酸橙\n’,‘芒果\n’,‘油桃\n’,‘橙色\n’,‘木瓜\n’,‘木瓜\n’,‘覆盆子\n’,‘草莓\n’,‘罗望子\n’,'umkolo\n',‘香草\n’,‘西瓜\n’,'xigua\n','yiessas\n','zapote blanco\n‘
#open file with list
infile = open("unsorted_fruits.txt", "r")
#open file writing to
outfile = open("sorted_fruits.txt", "w")
#create variable to work with list
all_lines = infile.readlines()
for line in all_lines:
print (line,)
#this function has sorted other list
def insertion_sort(list):
for index in range(1, len(list)):
value = list[index]
i = index - 1
while i >= 0:
if value < list[i]:
list[i+1] = list[i]
list[i] = value
i = i - 1
else:
break
#calling the function to sort and make it look nicer
insertion_sort(all_lines)
for word in all_lines:
if word.rstrip('\n'):
print(word.rstrip('\n'))
for word in all_lines:
if word.rstrip('\n'):
outfile.write(word.rstrip('\n'))
all_sorted = str(all_lines)
#write the sorted list to the file
outfile.write(all_sorted)
infile.close()
outfile.close()
exit() https://stackoverflow.com/questions/46944344
复制相似问题