0

could anyone please help me with the following problem. I have a task where I need to sort numbers from a txt file from lowest to highest value. No matter the combination of the numbers or length of text it needs to sort the numbers from lowest to highest. Any help will really be appreciated.

Text file (input.txt)

min:2,1,4,3,6,5

max:1,2,3,4,5,6

avg:1,2,3,4,5,6

I have written some code as follows but its just arranging the line title alphabeticaly

inputFile = open("input.txt", 'r')
lineList = inputFile.readlines()
lineList.sort()
print (lineList)
for line in lineList:
    print(line)
    with open('inputcopy.txt', 'a') as f:
        for line in lineList:
            lineList.sort()
            f.write(line)

Thank you for any help

Community
  • 1
  • 1
  • So do you want your script to ignore the non-number content of the file and just collect all the numbers that happen to be there? (i.e. 2, 1, 4, etc. but ignoring 'min:', 'max:', etc.?) – Grismar Feb 04 '20 at 06:52
  • Yes please i need to add the script in the output text file afterwards but i only need to arrange the numbers –  Feb 04 '20 at 07:13

2 Answers2

1

Since you're reading data from file, we have every line as a string. So, you need to use split method in combination int constructor.

This can be achieved using a list comprehension.

for line in lineList:
    numbers = [int(item) for item in line.split(':')[1].split(',')]

line.split(':')[1] gives as the string 2,1,4,3,6,5

Another split by comma separator gives us the list of numbers. I used int constructor because after split method we have them like strings.

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

You could use regex. Note that you need to either convert to int or use a custom function that considers the integer representation

for line in lineList:
   sorted_line = sorted(map(int, re.findall(r'\d+',line)))


for line in lineList:
   sorted_line = sorted(re.findall(r'\d+',line), key=lambda x:int(x))
abc
  • 11,579
  • 2
  • 26
  • 51