Search code examples
pythonmaxmin

How to find min/max values from rows and columns in Python?


I was wondering how can I find minimum and maximum values from a dataset, which is basically a text file. It has 50 rows, 50 columns.

I know I can set up a control loop (for loop to be specific) to have it read each row and column, and determine the min/max values. But, I'm not sure how to do that.

I think the rows and columns need to be converted to list first and then I need to use the split() function. I tried setting something up as follows, but it doesn't seem to work:

for x in range(4,50): # using that range as an example
    x.split()
    max(4,50)
    print x

New to Python. Please excuse my mistakes.


Solution

  • Try something like this:

    data = []
    with open('data.txt') as f:
        for line in f:                   # loop over the rows
            fields = line.split()        # parse the columns
            rowdata = map(float, fields) # convert text to numbers
            data.extend(rowdata)         # accumulate the results
    print 'Minimum:', min(data)
    print 'Maximum:', max(data)
    

    Note that split() takes an optional argument if you want to split on something other than whitespace (commas for example).