为什么append()不遵循if语句的条件?

2024-04-27 04:15:58 发布

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

这段代码应该检查相邻点是否作为points列表的一部分存在。你知道吗

  • points列表是给定的。你知道吗
  • check列表当前仅检查points列表的第一项。你知道吗
  • counted列表应该显示与第一个给定点相邻的points列表中存在的点。你知道吗
  • rowNbrcolNbr是与给定点相邻的点的以下条件。你知道吗
points = [[3,2],[4,2],[4,3],[5,2],[5,3],[6,4]]
temp = [[3,2],[4,2],[4,3],[5,2],[5,3],[6,4]]
check = []
counted = []


rowNbr = [1, -1, 0, 0, 1, 1, -1, -1]
colNbr = [0, 0, 1, -1, 1, -1, 1, -1]

check.append(points[0])

for j in range(len(check)):
    for i in range(len(rowNbr)):
        temp[j][0] = check[j][0] + rowNbr[i]
        temp[j][1] = check[j][1] + colNbr[i]


        if temp[j] in points:
            counted.append(temp[:])


print(counted)           

我要打印:[[4, 2], [4, 3]]

它打印出以下内容:

[[[2, 1], [4, 2], [4, 3], [5, 2], [5, 3], [6, 4]], [[2, 1], [4, 2], [4, 3], [5, 2], [5, 3], [6, 4]]]

如果在if temp[j] in points:循环中包含一个print(temp[j])行,它将打印corect坐标,但是counted列表是错误的,并且打印出所有内容。你知道吗

为什么会发生此错误?如何修复它?你知道吗


Tags: in列表forlenifcheckrangetemp
2条回答

counted.append(temp[:])每次执行temp数组时都会附加整个temp数组的一个副本,如果您只希望它附加temp[j]的一个副本,请改为执行counted.append(temp[j][:])。你知道吗

我认为您在引用temp[:](应该是counted.append(temp[j][:])而不是counted.append(temp[:]))时缺少一个元素:

points = [[3,2],[4,2],[4,3],[5,2],[5,3],[6,4]]
temp = [[3,2],[4,2],[4,3],[5,2],[5,3],[6,4]]
check = []
counted = []


rowNbr = [1, -1, 0, 0, 1, 1, -1, -1]
colNbr = [0, 0, 1, -1, 1, -1, 1, -1]

check.append(points[0])

for j in range(len(check)):
    for i in range(len(rowNbr)):
        temp[j][0] = check[j][0] + rowNbr[i]
        temp[j][1] = check[j][1] + colNbr[i]


        if temp[j] in points:
            counted.append(temp[j][:])


print(counted)     

相关问题 更多 >