Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List comprehension

I want to fill a list, according to another list with scores. I have found a way but was wondering whether it could be done with list comprehension as well.

I have a list mood_options with strings and a list with weekly_scores with integers. I use the integers from the weekly_scores as an index to pick from the mood_options list. Then, these elements picked from mood_options are put in a list called weekly_moods.

This I how I achieved it with a for loop:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    mood_options = ["awful", "bad", "meh", "good", "amazing"]
    weekly_scores = [2, 4, 1, 3, 4, 2, 4]

    weekly_moods = []

    for score in weekly_scores:
        weekly_moods.append(mood_options[score-1])

As I said, it works, but I have the feeling it can be more concise using list comprehension, however, I cannot figure out how.

>Solution :

Use:

weekly_moods = [mood_options[score-1] for score in weekly_scores]

Full Code

mood_options = ["awful", "bad", "meh", "good", "amazing"]
weekly_scores = [2, 4, 1, 3, 4, 2, 4]

weekly_moods = [mood_options[score - 1] for score in weekly_scores]
print(weekly_moods)

Output

['bad', 'good', 'awful', 'meh', 'good', 'bad', 'good']

References

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading