如何优化嵌套的 if 语句?我不能在这里使用 &&

有没有更好的方法可以写这个?我是 python 编码新手,我想改进以下代码行。我在这里包含了几行代码,但原始代码比这长得多(多个 if 语句)。任何指导/反馈都会有帮助。


    upperchar = #generate a char

    pwdlist.append(upperchar)

    if len(pwdlist) < length:

        upperchar2 = #generate a char

        pwdlist.append(upperchar2)

        if len(pwdlist) < length:

            lowerchar = #generate a char

            pwdlist.append(lowerchar)

            if len(pwdlist) < length:

                lowerchar2 = #generate a char

                pwdlist.append(lowerchar2)

                if len(pwdlist) < length:

                    char3 = #generate a char

                    pwdlist.append(char3)

在这里发布我的第一个问题,如果您需要更多信息,请问我。


慕雪6442864
浏览 47回答 1
1回答

HUWWW

假设您总是以相同的方式生成角色,那么这会起作用pwdlist = []while len(pwdlist) < length:&nbsp; &nbsp; pwdlist.append(generate_char())或者pwdlist = [generate_char() for _ in range(length)]然后,您可以将逻辑添加到此生成函数中,以根据随机值返回某些内容,例如def generate_char():&nbsp; &nbsp; from random import randrange&nbsp; &nbsp; x = randrange(4)&nbsp; &nbsp; if x == 0:&nbsp; &nbsp; &nbsp; &nbsp; return 'value a-z'&nbsp; &nbsp; elif x == 1:&nbsp; &nbsp; &nbsp; &nbsp; return 'value A-Z'&nbsp; &nbsp; elif x == 2:&nbsp; &nbsp; &nbsp; &nbsp; return 'value 0-9'&nbsp; &nbsp; elif x == 3:&nbsp; &nbsp; &nbsp; &nbsp; return 'punctuation'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python