我是一个高级PHP和Perl的家伙,但是Python对我来说是新的。我很喜欢学习!我写了下面的代码,但是我无法摆脱这样一种感觉:拥有“高级”Python技能的人可以更好地编写它。你是真正的蟒蛇吗?
请注意:我希望代码可读。Python应该是可读的-我们不是在这里编写Perl的人!(示例:我喜欢“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
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'

编辑:听从金德尔的建议。

10-08 14:36