Python主义者:有没有更好的方法用Python来编码这个



我是一个资深的PHP和Perl爱好者,但Python对我来说是新的。我很喜欢学习它!我写了下面的代码,但我无法摆脱这样一种感觉,即它可以由具有"高级"Python技能的人更好地编写。你们是真正的Python人吗?

请注意:我希望代码可读。Python被认为是可读的——我们不是在这里写Perl的人!(例如:我喜欢"工作日"是一个字符串而不是整数,这让它非常清楚)

import datetime
today = datetime.datetime.now()
weekday = today.strftime("%a")
hourmin = int(today.strftime("%H%M"))
print "today here is: " + today.strftime("%c") # for debug
if weekday == "Sat" or 
   (weekday == "Sun" and hourmin < 2000) or 
   (weekday == "Fri" and hourmin > 1630) or 
   (hourmin >= 1630 and hourmin < 2000) :
    print "bad time"
else:
    print "good time"

您可以将一个日期字符串映射到一个lambda,该lambda需要hourmin并确定它是否坏。例如:

# establish the "rules"    
bad_time = {
    'Sat': lambda h: True,    # always bad time!
    'Sun': lambda h: h < 2000,
    'Fri': lambda h: h > 1630,
}
# ... get your `weekday` and `hourmin` values
is_bad = bad_time.get(weekday, lambda h: (1630 <= h < 2000))(hourmin)
print 'bad time' if is_bad else 'good time'

edit:听从kindall的建议。

在python中,如果有不匹配的parens,则可以继续下一行,而不需要反斜杠。您还可以在一个布尔表达式中进行两次比较。

if (weekday == "Sat" or
    (weekday == "Sun" and hourmin < 2000) or
    (weekday == "Fri" and hourmin > 1630) or
    1630 <= hourmin < 2000):
    print "bad time"
else:
    print "good time"

我建议使用一个可以轻松确定时间是否在预定义范围内的类,然后将该类的实例放在字典中记录每天的时间是"糟糕的"。为了方便以后更改,也许可以使用几个预定义范围。

class hmrange(object):
    def __init__(self, start, end):
        self.start, self.end = start, end
    def __contains__(self, hm):
        return self.start <= hm < self.end
alldayhours  = hmrange(0000, 2400)
weekdayhours = hmrange(1630, 2000)
badhours = {
    'Sun': hmrange(0000, 2000)
    'Mon': weekdayhours
    'Tue': weekdayhours
    'Wed': weekdayhours
    'Thu': weekdayhours
    'Fri': hmrange(1630, 2400)
    'Sat': alldayhours
}
badtime =  hourmin in badhours[weekday]
import datetime
today = datetime.datetime.now()
weekday = today.strftime("%a")
hourmin = int(today.strftime("%H%M"))
print "today here is: " + today.strftime("%c") # for debug
days = ["Sun", "Fri"]
times = [2000, 1630]
if weekday == "Sat" or 
    weekday in days and hourmin < times[days.index(weekday)] or 
    2000 > hourmin >= 1630:
    print "bad time"
else:
    print "good time"

相关内容

  • 没有找到相关文章

最新更新