简体   繁体   English

Python列表理解错误

[英]Python list comprehension error

I want to order a list into months 我想订购一份清单,数月之内

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

This function works but i would like to use list comprehension instead 此功能有效,但我想改用列表理解

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

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

output - ['Jan', 'Feb', 'April'] 输出-['Jan','Feb','April']

I tried this but i get a syntax error and i am not sure why 我试过这个但是我收到语法错误,我不确定为什么

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

Try this 尝试这个

values = ["Sept","Oct"]

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

Your list comprehension syntax was off a bit. 您的列表理解语法有点差。

There are two different ways to do conditionals in list comprehensions, and it depends on whether you have an else clause: 在列表推导中有两种不同的条件处理方式,这取决于您是否具有else子句:

Without else clause: 没有else子句:

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

With else clause: 与else子句:

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

Note: These can also be combined: 注意:这些也可以组合:

[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]

which is equivalent to: 等效于:

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

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

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