我想创建一个函数,该函数将检查是否是执行操作的正确时间,但是我希望它具有灵活性,并检查作为函数输入的每对args的条件。我写了一些代码,理论上看起来应该是什么样子,现在我想弄清楚如何用代码编写。
def report_time(greater_than1=0, lower_than1=24,
greater_than2=0, lower_than2=24,
greater_than3=0, lower_than3=24,
...
greater_thanN=0, lower_thanN=24):
if greater_than1 < datetime.now().hour < lower_than1:
logger.info('Hour is correct')
return True
if greater_than2 < datetime.now().hour < lower_than2:
logger.info('Hour is correct')
return True
if greater_than3 < datetime.now().hour < lower_than3:
logger.info('Hour is correct')
return True
...
if greater_thanN < datetime.now().hour < lower_thanN:
logger.info('Hour is correct')
return True
用法示例:
foo = report_time(16, 18)
foo = report_time(16, 18, 23, 24)
foo = report_time(16, 18, 23, 24, ..., 3, 5)
答案 0 :(得分:2)
一个更好的选择是使函数仅接受一对参数,然后遍历函数的所有对外部,并检查是否在任何步骤上返回了True
:
def report_time(greater_than=0, lower_than=24):
return greater_than < datetime.now().hour < lower_than
start_times = [10, 12, 20]
end_times = [11, 15, 22]
for start, end in zip(start_times, end_times):
if report_time(start, end):
logger.info('Hour is correct')
break
valid_times = map(report_time, start_times, end_times)
if any(valid_times):
logger.info('Hour is correct')
此外,正如@AzatIbrakov在his comment to another answer中提到的那样,如果您使用元组会更好。在这种情况下,您可以使用filter
:
def within_limits(limits=(0, 24)):
return limits[0] < datetime.now().hour < limits[1]
time_limits = [(10, 11), (12, 15), (20, 22)]
if any(filter(within_limits, time_limits)):
logger.info('Hour is correct')
答案 1 :(得分:1)
您需要查看*args
:
def multi_arg_pairs(*args):
if len(args) % 2 == 1:
raise ValueError("arguments must be an even number")
for v1, v2 in zip(args[0::2], args[1::2]):
print(v1, v2)
# Do something with your value pairs
multi_arg_pairs(1, 2, 3, 4)
输出:
1 2
3 4