I have a little one-liner in my Rails app that returns a range of copyright dates with an optional parameter, e.g.:
我在我的Rails应用程序中有一个小内容,它返回一系列带有可选参数的版权日期,例如:
def copyright_dates(start_year = Date.today().year)
[start_year, Date.today().year].sort.uniq.join(" - ")
end
I'm moving the app over to Django, and while I love it, I miss a bit of the conciseness. The same method in Python looks like:
我正在将应用程序移到Django上,虽然我喜欢它,但我还是有点简洁。 Python中的相同方法如下所示:
def copyright_dates(start_year = datetime.datetime.today().year):
years = list(set([start_year, datetime.datetime.today().year]))
years.sort()
return " - ".join(map(str, years))
It's been years since I've touched Python, so I'm betting there's an easier way to do it. Any ideas?
自从我接触Python以来已经有好几年了,所以我认为有一种更简单的方法。有任何想法吗?
EDIT: I know lists and sets are a bit of overkill, but I want the following output assuming the code is run in 2009:
编辑:我知道列表和集合有点矫枉过正,但我希望以下输出假设代码在2009年运行:
copyright_dates() # '2009'
copyright_dates(2007) # '2007 - 2009'
copyright_dates(2012) # '2009 - 2012'
3 个解决方案
#1
5
from datetime import datetime
def copyright_dates(start_year = datetime.now().year):
return " - ".join(str(y) for y in sorted(set([start_year, datetime.now().year])))
#2
5
Watch out for the default parameter which is evaluated once. So if your web application runs over 12/31/09 without a restart, you won't get the expected output.
注意一次评估的默认参数。因此,如果您的Web应用程序在没有重新启动的情况下运行超过12/31/09,您将无法获得预期的输出。
Try:
def copy(start=None):
start, curr = start if start else datetime.today().year, datetime.today().year
return str(start) if start == curr else '%d - %d' % tuple(sorted([start, curr]))
#3
2
Lists and sets seem to be overkill to me.
列表和集合似乎对我来说太过分了。
How about this:
这个怎么样:
def copyright_dates(start=datetime.datetime.today().year):
now = datetime.datetime.today().year
return (start==now and str(now) or "%d - %d" % (min(start, now), max(start, now)))
#1
5
from datetime import datetime
def copyright_dates(start_year = datetime.now().year):
return " - ".join(str(y) for y in sorted(set([start_year, datetime.now().year])))
#2
5
Watch out for the default parameter which is evaluated once. So if your web application runs over 12/31/09 without a restart, you won't get the expected output.
注意一次评估的默认参数。因此,如果您的Web应用程序在没有重新启动的情况下运行超过12/31/09,您将无法获得预期的输出。
Try:
def copy(start=None):
start, curr = start if start else datetime.today().year, datetime.today().year
return str(start) if start == curr else '%d - %d' % tuple(sorted([start, curr]))
#3
2
Lists and sets seem to be overkill to me.
列表和集合似乎对我来说太过分了。
How about this:
这个怎么样:
def copyright_dates(start=datetime.datetime.today().year):
now = datetime.datetime.today().year
return (start==now and str(now) or "%d - %d" % (min(start, now), max(start, now)))