我是高级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"
答案 0 :(得分:6)
您可以将day字符串映射到需要hourmin的lambda,并确定它是否错误。例如:
# 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'
编辑:关注kindall的建议。
答案 1 :(得分:3)
在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"
答案 2 :(得分:3)
我建议使用一个类,让您轻松确定时间是否在预定义的范围内,然后将此类的实例放在字典中,以记录每天的时间是“坏”。也许使用几个预定义的范围以方便和以后更改。
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]
答案 3 :(得分:0)
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"