字典不可下标

2024-05-17 00:06:09 发布

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

我有一个大的代码,我需要在里面使用这个函数,这个函数非常简单,它把(dictint)作为参数,在里面创建一个字典,我们必须在程序运行时初始化它。 错误正好发生在candidate["permutation"] = stochastic_swipe(best["permutation"])行中。我已经检查过Best不是None,这里的None对象是candidate

def ILS(best, maxIter):
    while maxIter>0:
        candidate ={}
        candidate["permutation"] = stochastic_swipe(best["permutation"])
        candidate["cost"] = total_cost(candidate["permutation"])
        if candidate["cost"] < best["cost"]:
            best = candidate
        maxIter -=1

    return best

Best正在像那样通过 {'permutation': [0, 799, 334, 816], 'cost': 19208.973827922397}


Tags: 函数代码none参数字典candidatedictint
2条回答

你说“best”是一个列表,如果是的话,你“不能访问它的”元素,比如best["permutation"]

我强烈的猜测是,你没有把任何东西作为最好的价值来传递

显然,您正在使用None作为第一个参数调用此函数。我们可以从您的代码中看到candidate始终是一个字典,但直到行:

        best = candidate

执行时,best正是传递给函数的内容

相关问题 更多 >