我只想在复活中应用一个条件.我的数据 struct 如下

stages = {"stage_1": False, "stage_2":False, "stage_3":False,"state_4": False}

我想从中随机选取任何阶段,并将状态更改为True.但当真阶段的总数为3时,我想随机将真阶段更改为假阶段.但只有一次.然后它应该继续将阶段变为现实.当所有4个阶段都为真时.递归过程停止.

def process(stages):
    all_stages = [stage for stage, status in stages.items() if status == False]
    if len(all_stages) !=0:
        print(all_stages)
        select_ = random.choice(all_stages)
        print("\tselected stage: ",select_)
        
        stages[select_] = True
        process(stages)
    else:
        print("Done")
        print(stages)

process(stages)

这在不增加额外条件的情况下有效.我试过下面这个.但这是行不通的

def process(stages):
    all_stages = [stage for stage, status in stages.items() if status == False]
    if len(all_stages) !=0:
        print(all_stages)
        select_ = random.choice(all_stages)
        print("\tselected stage: ",select_)
        
        stages[select_] = True

        if len(all_stages) == 1:
            select_ = random.choice([stage for stage, status in stages.items() if status == True])
            stages[select_] = False
        process(stages)
    else:
        print("Done")
        print(stages)

process(stages)

推荐答案

代码是@NoBlockhit的建议

stages = {"stage_1": False, "stage_2":False, "stage_3":False,"state_4": False}

status = True
def process(stages):
    global status
    print(status)
    all_stages = [stage for stage, status in stages.items() if status == False]
    if len(all_stages) !=0:
        print(all_stages)
        select_ = random.choice(all_stages)
        print("\tselected stage: ",select_)
        
        stages[select_] = True

        if status:
            if len(all_stages) == 1:
                select_ = random.choice([stage for stage, status in stages.items() if status == True])
                stages[select_] = False
                status = False
        process(stages)
    else:
        print("Done")
        print(stages)

process(stages)

Python相关问答推荐

产生镜像输出的MSG算法输出

跳过包含某些键的字典

Gekko解算器错误results.json未找到,无法找出原因

使用decorator 重复超载

如何判断LazyFrame是否为空?

有什么方法可以避免使用许多if陈述

在Pandas 日历中插入一行

Pandas 填充条件是另一列

仿制药的类型铸造

使用miniconda创建环境的问题

在Polars(Python库)中将二进制转换为具有非UTF-8字符的字符串变量

Godot:需要碰撞的对象的AdditionerBody2D或Area2D以及queue_free?

有没有一种方法可以从python的pussompy比较结果中提取文本?

为什么抓取的HTML与浏览器判断的元素不同?

NumPy中条件嵌套for循环的向量化

多处理队列在与Forking http.server一起使用时随机跳过项目

如何指定列数据类型

启动带有参数的Python NTFS会导致文件路径混乱

Python—转换日期:价目表到新行

为什么'if x is None:pass'比'x is None'单独使用更快?