打印列表时,我有两个P后,每个其他

2024-05-14 13:07:36 发布

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

你好,我正在尝试生成一个代码(当我有两个p时停止),但它使我: TypeError:“NoneType”对象不可订阅 谢谢你的帮助! 我的代码:

import random as rd
def experience ():
    L=[]
    L.append(rd.choice(['P','F']))
    L.append(rd.choice(['P','F']))
    a=0
    b=1
    while L[a]!=L[b]!='P':
        a=b
        b=b+1
        L.append(rd.choice(['P','F']))
    return L

Tags: 对象代码importreturndefasrandomrd
1条回答
网友
1楼 · 发布于 2024-05-14 13:07:36

我不明白你提到的例外,但你确定你的退出条件是正确的吗?你知道吗

“while not(L[a]==L[b]=='p'):”如果你想在两个'p'之后退出,你会更正确吗?你知道吗

或者甚至可以“while not(L[a]=='p'and L[b]=='p'):”来提高可读性,因为同一语句中的两个“==”很容易被误解。你知道吗

顺便说一下,这是一个较短的实现,实际上不需要跟踪索引:

def experience():
    L = [rd.choice(['P', 'F'])]
    while True:
        L.append(rd.choice(['P', 'F']))
        if L[-1] == L[-2] == 'P':
            return L

相关问题 更多 >

    热门问题