Djanger
Djanger

Reputation: 143

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:

    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.

Upvotes: 1

Views: 50

Answers (2)

Dani Mesejo
Dani Mesejo

Reputation: 61930

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

Upvotes: 3

Seppukki
Seppukki

Reputation: 573

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

Upvotes: 1

Related Questions