如何检查脚本输入参数是否在可接受值列表中?

2024-04-23 14:44:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我这里有一个简单的例子,但它让我意识到我没有一个好的策略来处理更有趣的输入。如何检查(理想情况下是在O(1)时间内)输入是否在白名单中?你知道吗

import time

global wait_time_secs

def validateUsage(arg_list):
  """Validates that the user called this program correctly and teaches the
     expected usage otherwise"""
  global wait_time_secs    
  # Discard the first argument which is always the script name
  arg_list.pop(0)

  # Ensure the next argument exists and is valid
  if len(arg_list) < 1:
    teachUsage()
    sys.exit(0)

  wait_time_secs = int(arg_list.pop(0))
  # My hard-coded list of acceptable values.  How to do for non-trivial input?
  if ((10 == wait_time_secs) or (20 == wait_time_secs)) is not True:
    print "invalid parameter"
    teachUsage()
    sys.exit(0)

def main():
  validateUsage(list(sys.argv))
  time.sleep(wait_time_secs)

if __name__ == '__main__':
  main()

Tags: andtheiftimeismaindefsys
1条回答
网友
1楼 · 发布于 2024-04-23 14:44:44

一种方法是使用^{}包含所有可接受的值,如下所示:

acceptable_values = set([10, 20])

然后将条件更改为:

if wait_time_secs not in acceptable_values:
    teachUsage()

集合将确保O(1)查找。你知道吗

相关问题 更多 >