Home > Software engineering >  List comprehension
List comprehension

Time:11-11

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:

    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.

CodePudding user response:

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

CodePudding user response:

It can be written with a list comprehension:
[mood_options[i-1] for i in weekly_scores]
This takes an i from weekly_scores and uses it to take the correct item out mood_options

  • Related