mercredi 7 avril 2021

A large if ... elif in python I want to improve in one line

I have this long conditional statement

num = ['One', 'Five', 'Three', 'Four']
rating = []
for num in num:
    if  num == 'One':
        rating.append('1/5')
    elif num == 'Two':
        rating.append('2/5')
    elif num == 'Three':
        rating.append('3/5')
    elif num == 'Four':
        rating.append('4/5')
    elif num == 'Five':
        rating.append('5/5')
print(ratings)

and returns

['1/5', '5/5', '3/5', '4/5']

But I would like to improve this because I want this to be part of a line of code and this is too much to add.

I'm making some attempts with lambda functions but I have not made it yet. Thanks so much for your help!

Aucun commentaire:

Enregistrer un commentaire