Home > Software design >  '>=' not supported between instances of 'str' and 'int'
'>=' not supported between instances of 'str' and 'int'

Time:11-09

students = ['Ally',100,
           'Emo',88,
           'Stefan',70,
           'George',60,
           'Alex',45,
           'Vasil',32,
           'Daniel',0]
passed_students = list(filter(lambda x: x >= 60, students))
print(passed_students)

What did I do wrong,I also added 'str' before student,it didn't work so i added int but that also didn't work.

CodePudding user response:

You data structure for students seems wrong. I suggest to convert it to dictionary, then the filtering will be easier:

# convert students list to a dictionary:
students = dict(zip(students[::2], students[1::2]))

# students is now
#{
#    "Ally": 100,
#    "Emo": 88,
#    "Stefan": 70,
#    "George": 60,
#    "Alex": 45,
#    "Vasil": 32,
#    "Daniel": 0,
#}

# now you can use dict-comprehension to do a filtering:
passed_students = {k: v for k, v in students.items() if v >= 60}
print(passed_students)

Prints:

{"Ally": 100, "Emo": 88, "Stefan": 70, "George": 60}

CodePudding user response:

Since the list alternates between names and scores, you need to iterate over the list in steps of 2.

passed_students = [students[i] for i in range(0, len(students), 2) if students[i 1] >= 60]
  • Related