# RaggedArray Example # A ragged array is an array whose rows need not be the same length. # Define a method that reads a ragged array from a file. # Then use the sum_array method used in the Array2 Example to sum # each row of the ragged array, creating a new array of the row sums. # Define method to read a ragged array def read_ragged_array(the_filename): # Initialize ragged array ragged_array = [ ] # Open input file and read first line f = open(the_filename, "r") line = f.readline( ) # Keep processing lines until end of file is reached. while line: fields = line.split(",") row = [ ] # Append each field item to the row array for field in fields: row.append(float(field.strip( ))) # When finished constructing row, append # to ragged_array. ragged_array.append(row) # Read next line line = f.readline( ) # When finished reading file, return ragged array return ragged_array # Test script ragged_array = read_ragged_array("values2.txt") print("Ragged Array:") print(ragged_array) # Input file: values2.txt 45.7,23.9,112.0,4.5 65.3,56.1,239.3 11.8 53.2,65.7