因此,我正在尝试取回 n 商店的列表,以使他们成为邻居,然后在必要时,然后,在邻居的邻居中。以下是用于计算此列表的代码,称为位置。商店的编号为1到10。
在这种情况下,每个商店都有4个邻居。这种关系是在词典中随机设置的,称为邻居。
import random
shops = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
neighbours = {}
for i in shops:
neighbours[i] = random.sample(shops, 4)
while i in neighbours[i]:
neighbours[i] = random.sample(shops, 4)
print (neighbours)
shop_zero = random.randrange(1,11)
locations = [shop_zero]
neighborhd = neighbours[locations[0]]
n=10
while len(locations) < n:
if not neighborhd:
print('if statement')
neighborhd = neighbours[random.choice(locations)]
print (neighborhd)
print('while loop')
ne = neighborhd.pop(0)
if ne not in locations:
locations.append(ne)
print (locations)
问题在于代码有时有时,但通常会给我一个索引错误:
IndexError: pop from empty list
对于感兴趣的人,以下是邻居字典的输出:
{1: [7, 5, 4, 9], 2: [5, 6, 3, 7], 3: [10, 8, 7, 6], 4: [7, 8, 10, 2], 5: [3, 6, 1, 9], 6: [5, 1, 10, 3], 7: [3, 8, 6, 2], 8: [10, 4, 9, 7], 9: [6, 5, 3, 2], 10: [3, 5, 8, 7]}
我已经添加了一些打印语句,以使工作示例更具信息性。正如我之前说的那样,它确实经常起作用,但主要是给出索引错误。请帮助?
P.S。我意识到,最终的列表并不总是会给我群集,而是从邻居到邻居的途径。这对我正在进行的项目很好。
基本上,您在neighborhd = neighbours[random.choice(locations)]
中有问题。它还返回空列表。因此,您需要几乎没有改变。if neighborhd:
到pop
之前只检查它不是空列表。
import random
shops = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
neighbours = {}
for i in shops:
neighbours[i] = random.sample(shops, 4)
while i in neighbours[i]:
neighbours[i] = random.sample(shops, 4)
print (neighbours)
shop_zero = random.randrange(1,11)
locations = [shop_zero]
neighborhd = neighbours[locations[0]]
n=10
while len(locations) < n:
if not neighborhd:
print('if statement')
neighborhd = neighbours[random.choice(locations)]
print (neighborhd)
print('while loop')
if neighborhd:
ne = neighborhd.pop(0)
if ne not in locations:
locations.append(ne)
print (locations)
我更改了您的代码帮助调试,您可以在下面看到。如果您运行此操作,则发现当异常抛出时,"邻居"词典将空列表作为某些值。这意味着可以将"邻居"从"邻居"中重新填充,因此仍然是空的。
import random
shops = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
neighbours = {}
for i in shops:
neighbours[i] = random.sample(shops, 4)
while i in neighbours[i]:
neighbours[i] = random.sample(shops, 4)
print (neighbours)
shop_zero = random.randrange(1,11)
locations = [shop_zero]
neighborhd = neighbours[locations[0]]
n=10
while len(locations) < n:
if not neighborhd:
print('if statement')
neighborhd = neighbours[random.choice(locations)]
print (neighborhd)
print('while loop')
try:
ne = neighborhd.pop(0)
except IndexError:
raise IndexError("Attempt to pop from neighborhd which has content %s, formed from neighbours which has content %s" % (neighborhd, neighbours))
if ne not in locations:
locations.append(ne)
print (locations)