我想订购清单到几个月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) –