Find the average, maximum, of the three groups separated by a specific delimiter in the txt file

Asked 1 years ago, Updated 1 years ago, 118 views

Notepad file txt file

======
1.234234

4

5

3


=======


=======

2323

343

=======

In this way, we have to divide into three groups according to ====== and find the average or maximum value of those values, but I'm not sure what code can distinguish this segment. The second group means there's nothing inside.

open txt

2022-09-21 10:00

1 Answers

This allows you to put numbers in each group. You can then find the average and maximum values of the numbers registered in each group.

If you make the above written content into Python code, it's roughly as follows.

num_groups = []
with open('dat.txt', 'rt') as f:
    group = []
    first_sep = True
    for line in f.readlines():      
        line = line.strip()          
        if '===' in line:
            if not first_sep: 
                num_groups.append(group[:])
            group = []
            first_sep = False
            continue
        try:
            num = float(line)
            group.append(num)
        except:
            continue

The average and maximum are easy, so do it yourself.


2022-09-21 10:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.