Removing elements from a list in Python [duplicate]

0

Basically I want to remove elements from a list by one criterion. For examples: I have a room with N students, I will store those students' note in a list and compare these notes with the cut note that I type. If the student's grade is greater than or equal to the cut grade I leave it in the list, otherwise I remove it from the list

    
asked by anonymous 29.05.2017 / 04:34

1 answer

1
  

Only after @ AndersonCarlosWoss identifies that there was another identical question, I saw that his answer is much wider than mine. See link

Use list comprehension

Be sala a list of students. Be a student defined as having the nota attribute. Be corte the variable of the cutoff. So we can get the list of approved students as follows:

aprovados = [ aluno for aluno in sala if aluno.nota >= corte ]

So, we get the list of approved students in a room without having to change the original value of the room list.

EDIT

My initial reading of the problem was that you had a list of students that needed to be filtered by note , but reread the question and also, taking into account the comment from the AP, I noticed that you have a list of notes . My previous code continues with the valid form, however we need to review some of the concepts used.

As we have a list of notes, I have no object aluno with attribute nota , only a number that already indicates the student's note. So:

Be sala a list of student grades. Be corte the variable of the cutoff. So we can get the list of approved students as follows:

notas_aprovadas = [ nota for nota in sala if nota >= corte ]
    
29.05.2017 / 05:41