我想訂購清單到幾個月Python列表理解錯誤
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"]
輸出 - [「月」,'二月','四月']
我試過這個,但我得到一個語法錯誤,我不知道爲什麼
sorted_ = [month if month in values for month in months]
它看起來像你的'if'是放錯了地方:'sorted_ = [月爲月個月,如果在一個月值]' – mgilson
@mgilson生命的救星! –
你實際上並不需要理解......'sorted(values,key = months.index)'。但每個'list.index'調用是O(n) –