简体   繁体   English

KeyError: (1, 1) 尝试使用 python 列表理解和 google-ortools

[英]KeyError: (1, 1) when trying to use python list comprehension and google- ortools

I used this example here if/else in a list comprehension for list comprehension with if-else to create a constraint for the sum .我在if/else 列表推导中使用了此示例,以使用 if-else 为列表推导创建 sum 约束。

This is the piece of code that triggers the error这是触发错误的一段代码

    for j in range(1, m+1):
        solver.Add(solver.Sum([0 if c[i][j]==0 else x[i, j] for i in range(1, n+1)]) <= 1)

x is a dict defined earlier and c[i][j] is a boolean that is 1 when (i,j) is in the permitted. x 是前面定义的字典,而 c[i][j] 是一个布尔值,当 (i,j) 在允许范围内时为 1。 But when (i,j) is in permitted x[i,j] holds a variable in ortools .但是当 (i,j) 被允许时, x[i,j] 在 ortools 中保存一个变量。 So what I am saying is that I want for this particular j to sum x[i,j]'s , if x[i,j] exists then ok if it does not then just add 0 .所以我要说的是,我希望这个特定的 j 对 x[i,j]'s 求和,如果 x[i,j] 存在,那么如果它不存在则可以,那么只需添加 0 。

    c = [[0]*(m+1)]*(n+1)
    for (i,j) in permitted:
        c[i][j]=1

    x = {}
    for (i,j) in permittted:
            x[i, j] = solver.IntVar(0, 1, '')

There is a problem with how your boolean list is defined.您的布尔列表的定义方式存在问题。 Consider this:考虑一下:

In [1]: c = [[0] * 2] * 3

In [2]: c
Out[2]: [[0, 0], [0, 0], [0, 0]]

In [3]: c[1][1] = 1

In [4]: c
Out[4]: [[0, 1], [0, 1], [0, 1]]

In c , you actually have the same inner list repeated, so assigning a single value is reflected in each copy.c中,您实际上重复了相同的内部列表,因此分配单个值会反映在每个副本中。 Hence your checks for c[i][j] == 0 may not produce the results you expected.因此,您对c[i][j] == 0的检查可能不会产生您预期的结果。

Try changing the definition of c to:尝试将c的定义更改为:

c = [[0] * (m + 1) for _ in range(n + 1)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM