Py学习  »  Python

Python:列表。remove()有线地

Jokermania • 3 年前 • 1065 次点击  
def get_variables(cells):
    domains = [1,2,3,4]
    variables = {}
    for cell in cells:
        if(cell == "C11"):
            variables[cell] = [1]
        elif(cell == "C22"):
            variables[cell] = [2]
        elif(cell == "C33"):
            variables[cell] = [3]
        elif(cell == "C44"):
            variables[cell] = [4]
        else:
            variables[cell] = domains

cells = ['C'+x+y for x in "1234" for y in "1234"]
variables = get_variables(cells)
csp = CSP(variables, constraints, assigned)
pprint(csp.variables)
csp.variables["C12"].remove(1)
print(csp.variables["C13"])
output: 
{'C11': [1],
 'C12': [1, 2, 3, 4],
 'C13': [1, 2, 3, 4],
 'C14': [1, 2, 3, 4],
 'C21': [1, 2, 3, 4],
 'C22': [2],
 'C23': [1, 2, 3, 4],
 'C24': [1, 2, 3, 4],
 'C31': [1, 2, 3, 4],
 'C32': [1, 2, 3, 4],
 'C33': [3],
 'C34': [1, 2, 3, 4],
 'C41': [1, 2, 3, 4],
 'C42': [1, 2, 3, 4],
 'C43': [1, 2, 3, 4],
 'C44': [4]}
[2, 3, 4]

它应该从“C12”中删除1,而不是从“C13”中删除。为什么?我猜和记忆位置有关吧?这真让我抓狂。任何建议都将不胜感激!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131944
 
1065 次点击  
文章 [ 3 ]  |  最新文章 3 年前
Jokermania
Reply   •   1 楼
Jokermania    3 年前

谢谢你的评论!

我终于明白了:而不是 variables[cell] = domains 我应该这么做 variables[cell] = domains[:] ,将副本分配给 variables[cell]

多好的一课啊!

Jewel_R
Reply   •   2 楼
Jewel_R    3 年前

试试这个

desired_key = 'C12'
for key in csp.keys():
  if key == desired_key:
    del csp[key][0]


print(csp)
``
scr
Reply   •   3 楼
scr    3 年前

我想“C12”和“C13”不包含不同的列表,而是同一个列表。这意味着无论你如何修改其中一个,另一个都会受到同样的影响。

要清楚地看到这一点,请打印 csp.variables 在最后,而不仅仅是“CSP12”。

你能发布你的代码来生成dict吗?这样我们就可以帮你找到错误了?

编辑:谢谢你的代码。

错误是这样的:

            variables[cell] = domains

因为每 variable[cell] 同样的清单。这是一个 mutable type .因此,当它被修改时,它将被就地修改。

要解决这个问题,可以给单元格提供副本或切片,它们是不同的对象:

            variables[cell] = domains.copy()

            variables[cell] = domains[:]