Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Find the Minimum and Maximum value of the each row from the text file in Python file handling?

I have a text file in the folders, the file has data many numbers. I need to find the Minimum and Maximum values from each row from that file using Python. And the result should look like this:

Example numbers from .txt file

10  2  3  5  9 12 15
 5  9  4  8 10 98 15
23 19 89 71 56 20 11

Result like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[(min,max)from first row, (min,max)from second row,.........]

Expected Result

[(2,15),(4,98),(11,89),.....]

>Solution :

Loop over the lines, split. convert to int and use min / max

with open ('in.txt') as f:
  data = []
  for line in f:
    numbers = [int(x) for x in line.strip().split()]
    data.append((min(numbers),max(numbers)))
print(data)

output

[(2, 15), (4, 98), (11, 89)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading