拆分后如何对文本文件中的数字进行排序



有人可以帮我在拆分后从文本文件中对数字进行排序。我有以下文本文件,我需要从低到高对数字进行排序。无论序列或数值如何,我都需要从低到高对它们进行排序。

到目前为止,我有以下代码,但它仍然没有对数字进行排序。任何帮助都会很棒。谢谢。

文本文件(输入.txt(:

最小:2,1,4,3,6,5

最大:1,2,3,4,5,6

平均:1,2,3,4,5,6

到目前为止我的代码:

inputFile = open("input.txt", 'r')
lineList = inputFile.readlines()
print (lineList)
for line in lineList:
numbers = [int(item) for item in line.split(':')[1].split(',')]
numbers.sort()
with open('inputcopy.txt', 'a') as f:
for line in lineList:
numbers.sort()
f.write(line)     

试试这个:

inputFile = open("input.txt", 'r')
lineList = inputFile.readlines()
print (lineList)
fileHandle = open('inputcopy.txt', 'a')
for line in lineList:
numbers = [int(item) for item in line.split(':')[1].split(',')]
numbers.sort()
fileHandle.write("%sn" % numbers)  
fileHandle.close()

清理一下

for line in lineList:
# Split your line into your label and number list
label, numbers = line.strip().split(':')
# Convert the numbers into integers and sort them
numbers = [int(item) for item in numbers.split(',')]
numbers.sort()
# Convert the numbers back into a comma-delimited string
numbers = ','.join(map(str, numbers))
with open('inputcopy.txt', 'a') as f:
# Write your data back out
f.write('%s:%sn'.format(label, numbers))

相关内容

  • 没有找到相关文章

最新更新