2020-11-29

Arrange a file/output in numerical order, based on the first digit

I have developed a program that produces an average value for measurements on a unit circle. The text files I use, that contains the data of the measurements, can consist of several batches (by that I mean several different measurement occasions) that have two measurements in each. The batch number is always the first one in each line, for example the text file can look like this:

(1), x, y, 10
(1), x, y, 5
(3), x, y, 70
(3), x, y, 10
(2), x, y, 5
(2), x, y, 70

And the number within () is the number of the batch. And when python gives me these average values it gives them in the order that they are written in the text file. In this case, it would show in the order (1), (3) and (2) but I want python to give me these in numerical order instead. I guess I can somehow code so that when python opens the file it reads it in numerical order after the first digit in each line? But how can i enter this?

My current code is:

def collect_data(filename):

    data = [] # Or data = {} #definierar denna först

    with open(filename, 'r') as h:
        for line in h:
            four_vals = line.split(',')
            batch = four_vals[0]
            if not batch in data:
                data[batch] = []
            try:  
                data[batch] += [(float(four_vals[1]), float(four_vals[2]), float(four_vals[3]))] # Collect data from an experiment 
            except ValueError:
                print("String not a float")
    return data

def average(data):

    for batch, sample in data.items(): 
        if len(sample) > 0:
            n = 0
            x_sum = 0
            for (x, y, val) in sample:
                if x**2 + y**2 <= 1:
                    x_sum += val
                    n += 1
            average = x_sum/n
            zero_data = False
        else:
            zero_data = True
       
        print_average(batch, average, zero_data)
        
def print_average(batch, average, zero_data):

    if zero_data == False:
        print(batch, "\t", average)
    else:
        print(batch, "\tNo data")

Edit Since I have defined four_vals[0] as the first value in each line (the number of the batch) I believe that I do have to sort by four_vals[0] somehow, but how?



from Recent Questions - Stack Overflow https://ift.tt/3lhnbUi
https://ift.tt/eA8V8J

No comments:

Post a Comment