Python列表理解错误

时间:2017-03-17 16:59:44

标签: python list-comprehension

我想订一个列表到几个月

months = ["Jan", "Feb", "March", "April",
          "May", "June", "July", "Aug",
          "Sept", "Oct", "Nov", "Dec"]

此功能有效,但我想使用列表理解

def order(values):
    sorted = []
    for month in months:
        if month in values:
            sorted_.append(month)
    return sorted_

order(["April","Jan", "Feb"]

输出 - [' Jan',' 2月',' 4月']

我试过这个,但是我遇到语法错误,我不知道为什么

sorted_ = [month if month in values for month in months]

2 个答案:

答案 0 :(得分:1)

试试这个

values = ["Sept","Oct"]

sorted_ = [month for month in months if month in values]

您的列表理解语法略有不同。

答案 1 :(得分:1)

在列表推导中有两种不同的方法来处理条件,这取决于你是否有一个else子句:

没有else子句:

[x for x in y if x == z]
[result for element in list if conditional]

使用else子句:

[x if x == z else -x for x in y]
[result if conditional else alternative for element in list] 

注意:这些也可以组合使用:

[x if x.name == z else None for x in y if x is not None]
[result if conditional2 else alternative for element in list if conditional1]

相当于:

total_result = []
for x in y:
    if conditional1:
        if conditional2:
            total_result.append(result)
        else:
            total_result.append(alternative)