vendredi 25 août 2017

Selective averaging in python

so this code just randomises the list 1,2,3,4(x4) then writes it out into text file and reads it back out. It prints all the 16, however i was wondering if there was a way make 4 groups of 4 out of the 16, then I could define it and call them individually and take an average of only 4 of them.

import random
members = 5
participants=[1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4]
random.shuffle(participants)
with open("myfile1.txt",'w') as tf:
    for i in range(len(participants) // members + 1):
        group = participants[i*members:i*members + members]
        for participant in group:
            tf.write(str(participant))
            tf.write("\n")

with open("myfile1.txt",'r') as tf:
    for line in tf.readlines():
        print(line)

def ing():
    with open('myfile1.txt','r') as file:
        print(sum(list(map(int,[elem for elem in file.read().split('\n') if elem!='']))))

Sorry its a bit waffly, basically want to take an average of the first 4 numbers it spits out!

Thanks!




Aucun commentaire:

Enregistrer un commentaire