以下代码摘自较大的程序;无法丢弃一个 - 总是(0,4) - 在16种可能性中:对所有可能性应用相同的逻辑。完全莫名其妙。谢谢你的帮助。
#!/usr/bin/env python3
def mystery():
#dict generated from a 4x4 array of tkinter canvas rectangles
geo = {1: (1, 1), 2: (1, 2), 3: (1, 3), 4: (1, 4),
5: (2, 1), 6: (2, 2), 7: (2, 3), 8: (2, 4),
9: (3, 1), 10: (3, 2), 11: (3, 3), 12: (3, 4),
13: (4, 1), 14: (4, 2), 15: (4, 3), 16: (4, 4)}
#the next two lines needed to get at the key from the values index,
#to generate a dictionary of neighbours ... used later in the program
geo_k = list(geo.keys()) #(list of keys)
geo_v = list(geo.values()) #(list of values)
#print(geo_v)
counter = 0
for k in geo:
id = geo[k]
poss_n = [(id[0],id[1]-1),(id[0],id[1]+1), # possible neighbours
(id[0]-1,id[1]),(id[0]+1,id[1])]
# print("initial ", poss_n)
for each in poss_n:
if each not in geo_v:
print(each)
counter += 1
poss_n.remove(each)
else: pass
# print("final ", poss_n)
print(counter)
mystery()
答案 0 :(得分:0)
虽然元素拥有for循环,但您无法将其从列表中删除,我建议您按照for each in poss_n[:]
的方式执行某些操作,这将创建列表的副本供您迭代同时仍允许您从原始元素中删除元素。