简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM