Reputation: 1427
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]
Upvotes: 1
Views: 608
Reputation: 7952
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)
Upvotes: 1
Reputation: 1338
Try this
values = ["Sept","Oct"]
sorted_ = [month for month in months if month in values]
Your list comprehension syntax was off a bit.
Upvotes: 1