简体   繁体   中英

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

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:

Without else clause:

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

With else clause:

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

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