简体   繁体   English

列表理解

[英]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.我有一个带有字符串的列表mood_options和一个带有整数的weekly_scores列表。 I use the integers from the weekly_scores as an index to pick from the mood_options list.我使用来自weekly_scores的整数作为从mood_options列表中选择的索引。 Then, these elements picked from mood_options are put in a list called weekly_moods .然后,从mood_options中挑选的这些元素被放入一个名为weekly_moods的列表中。

This I how I achieved it with a for loop:这是我如何通过 for 循环实现的:

    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这需要从我weekly_scores并用它来拿出正确的项目mood_options

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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