简体   繁体   中英

How to find the minimum and maximum value of the each row from the text file in 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

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

Expected Result

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

The easiest way that I can think of is with pandas. Read the file into a dataframe and zip the min and max values together.

from io import StringIO # import just for the example
import pandas as pd
s = """10  2  3  5  9 12 15
 5  9  4  8 10 98 15
23 19 89 71 56 20 11"""

# df = pd.read_csv('/path/to/file.txt', sep='\s+', header=None)
df = pd.read_csv(StringIO(s), sep='\s+', header=None)
list(zip(df.min(axis=1), df.max(axis=1)))  # -> [(2, 15), (4, 98), (11, 89)]

One option is to read each line, split on spaces, convert from strings to ints, and add to a list. Then use min and max to find the relevant numbers:

with open('file.txt') as fil:
  results = []
  for line in fil:
    nums = [int(x) for x in line.strip().split()]
    results.append((min(nums), max(nums)))

print(results)
# [(2, 15), (4, 98), (11, 89)]

There are many ways to do this, but what first comes to my mind is to use pandas and its read_fwf function (fixed-width columns). Looking at your example.txt file the numbers are separated by 2-3 spaces so you can't use one specific separator (unless it is a \t - then use pd.read_csv()). After that you can:

with open("textfile.txt", 'r') as file:
    df = pd.read_fwf(file, colspecs=[widths_of_your_colums])

And later you can use the algorithm you described.

list = [(min(row), max(row)) for row in df]

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)]
with open("file.txt", "r") as f:
    num_list = [list(map(lambda x: int(x), line.strip().split())) for line in f]
out = [(min(li), max(li)) for li in num_list]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM