Home > OS >  how to write a for loop in more compact way in python
how to write a for loop in more compact way in python

Time:12-13

I want to make this code more compact...is there a way to do it

for line in  Qlines: #a loop that will read each line and store each given item in this case students and their marks to be stored in their given variables mentioned above
    eneq = line.split(';', 1) #splits the each line from the semicolon ";" 
    students.append(eneq[0]) #for each index 0 every line which would students names there will stored in a list format in the [] we created above and store in student variable and same thing applied to variable marks
    marks.append(eneq[1]) #for each index 1 every line which would be marks of students there are stored in variable marks

CodePudding user response:

You can construct a list of pairs and then transpose it using the zip(*x) idiom:

students, marks = zip(*(line.split(';', 1) for line in Qlines))

This leaves students and marks as tuples. If you absolutely need lists, you can convert them manually:

students = list(students)
marks = list(marks)

Alternatively, you can do it as part of the original one-liner:

students, marks = map(list, zip(*(line.split(';', 1) for line in Qlines)))

CodePudding user response:

This might help you. It is a more compact way of implementing. But note that compactness might make it harder to read and also more error prone. This way of coding is also inefficient because it iterates over the list twice. But feel free to try and know different ways of coding in python.

students, marks = [ line.split(';', 1)[0] for line in Qlines ], [ line.split(';', 1)[1] for line in Qlines ]
  • Related