I have a list which has the number of marks students have.
s = [50,62,15,76,57,97,82,99,45,23]
I want to grade students according to marks:
<40 - Fail
>50 - A Grade
>75 - A++ Grade
I can do this with iterating loops or I can find every list using lambda. for example :
>>> filter(lambda x:x>=50, s)
[50, 62, 76, 57, 97, 82, 99]
But, in the filter, I can work with only one function at a time (for example : marks greater than 50). Is there way where I can use filter and lambda and get required result in one line? Expecting the output as marks with grade. (ex : 50 - A, 62 - A, 76 - A++ ...)
Define a function that takes a mark and returns a human readable representation, you can use larsmans's expression or this one:
def grade(i):
if i<40: return "Fail"
if i>75: return "A++"
if i>50: return "A"
Use string.format to format each entry and map to iterate over all of them:
li = map(lambda x: "{0} - {1}".format(x, grade(x)), s)
The resulting list now contains strings in the desired format.
for i in li: print i
# output
50 - None
62 - A
15 - Fail
76 - A++
57 - A
97 - A++
82 - A++
99 - A++
45 - None
23 - Fail
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With