【问题标题】:Python if statement optimisationPython if 语句优化
【发布时间】:2022-02-10 06:48:08
【问题描述】:

我正在制作一个非常基本的密码生成器,它会询问用户他们想要的密码中的某些内容(例如,用户可以选择是否需要标点符号)。我已经完成了这个程序,它运行得非常好,但它包含了一部分 if 和语句:

if p == "N" and ucl == "N" and lcl == "N":
    print("Invalid requirements ")
if p == "N" and ucl == "N" and lcl == "Y":
    x = lclList
    generate(x)
if p == "N" and ucl == "Y" and lcl == "N":
    x = uclList
    generate(x)
if p == "N" and ucl == "Y" and lcl == "Y":
    x = uclList + lclList
    generate(x)
if p == "Y" and ucl == "Y" and lcl == "Y":
    x = pList + uclList + lclList
    generate(x)
if p == "Y" and ucl == "N" and lcl == "Y":
    x = pList + lclList
    generate(x)
if p == "Y" and ucl == "Y" and lcl == "N":
    x = pList + uclList
    generate(x)
if p == "Y" and ucl == "N" and lcl == "N":
    x = pList
    generate(x)

正如我所说,它运行良好,但看起来非常混乱且效率低下 - 我已经可以想象如果我使用 4 个要求会变得多么令人费解,而且上帝禁止了。是否有另一种编程方式可以使其可重复且更高效?

旁注,这几乎是我编写的第一个功能齐全的程序,所以如果我违反了日内瓦的一些编程惯例,请不要感到震惊。

【问题讨论】:

  • 您可以使用字典,它在 Python 中用作 switch case。

标签: python if-statement optimization passwords


【解决方案1】:

您可以将x 初始化为一个空列表,然后根据用户的选择,添加他们想要添加的内容:

x = []


if lcl == "Y":
    x += lclList
if ucl == "Y":
    x += uclList
if p == "Y":
    x += pList

generate(x)

【讨论】:

  • @KellyBundy 哦,我从上往下看,所以在第二个 if 语句中添加了lclList,在第三个中添加了uclList,在第五个中添加了pList .然而,在这种情况下,顺序并没有真正的区别。
【解决方案2】:

这是你的第一个功能齐全的程序,所以我会给你一些提示:

  1. 使用布尔值 (True/False) 来确定是或否的状态(当前为字符串)。
  2. 当嵌套独占的 if 语句时,请使用 elif。

您的代码(已更正)应如下所示(假设 p、lcl 和 ucl 是布尔值,而不是字符串):

# Init empty list.
x = []

# Append elements to your list.
if lcl:
    x += lclList
if ucl:
    x += uclList
if p:
    x += pList

# Check if selections are valid (x won't be an empty list, you can use if statement too) or print error message.
if x:
    generate(x)
else:
    print("Invalid requirements ")

希望这可以帮助您改进编码!

【讨论】:

  • 感谢您的建议,但该程序需要用户输入字符串来选择他们想要的内容 - 将其转换为布尔值(我假设,如果我错了,请告诉我)需要使用另一组 if 语句,因此将其保留为字符串可能会更容易(查看 marco breemhars 的答案)。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-18
  • 2010-09-07
  • 2013-09-17
  • 2017-06-16
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
相关资源
最近更新 更多