I'm new in Python and consequently I am searching for a specific solution for code development. I already asked some pythonic question today and want to present my whole problem. I have found some solution, but I really have interest to develop easier and clearer code in Python, so all improvements are welcome.
For example, in some school, the students are ordered to some of 3 different classes. Now I have some set of graduated students and want to know, how many graduated students are in some class.
I create next code:
physic = ['id_1', 'id_2', 'id_4']
chemistry = ['id_5', 'id_7']
math = ['id_3', 'id_8', 'id_9']
graduatedPhysic = []
graduatedChemistry = []
graduatedMath = []
classes = [physic, chemistry, math]
graduated = [graduatedPhysic, graduatedChemistry, graduatedMath]
Every class has the different number of students (given by students IDs) and gratuated Classes are at the first empty. I combine it also to list of lists.
Then I use my code:
graduatedlist = ['id_2', 'id_5', 'id_7']
for stud in graduatedlist:
for pos1 in range(len(graduated)):
for pos2 in range(len(classes[pos1])):
if stud.find(classes[pos1][pos2]) != -1:
graduated[pos1].append((stud))
This code works, but does not look great... I would be very grateful for comments! For example, I tried to implement the idea with itertools.product():
for item_1, item_2 in itertools.product(range(len(graduated)), range(len(classes[item_1])):
I have a problem with a declaration of item_1
.
I have also a feeling that the lists isn't the best solution for implementation, but for DataFrame I need the column of similar length and every class can have the different number of the students.
For the special interest are two points:
- How I really can improve my
for
-loop? - What I can use instead of list declaration?
gratuated
and the variableitem
is not defined anywhere). \$\endgroup\$