【发布时间】:2016-12-04 13:51:00
【问题描述】:
所以我试图找回 n 个商店的列表,以便它们是邻居,然后,如果有必要,是邻居的邻居。下面是用于计算此列表的代码,称为locations。商店的编号从 1 到 10(含)。
在这种情况下,每个商店有 4 个邻居。这种关系是在名为neighbours的字典中随机设置的。
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]}
我添加了一些打印语句以使工作示例提供更多信息。正如我之前所说,它确实经常工作,但大多数情况下它会给出索引错误。 请帮忙?
附:我意识到结果列表并不总是给我集群,而是一条从邻居到邻居的路径。这对我正在进行的项目来说很好。
【问题讨论】:
-
在
pop(0)之前放一个print(neighborhd)看看它的价值。 -
您似乎假设
neighborhd = neighbours[random.choice(locations)]行将始终为您提供非空列表。我看不出有任何理由证明这是真的。你能澄清你的推理吗? -
@A.Far 请在下面看看我的回答。谢谢
-
@MarkDickinson 我已经填写了
neighbours字典,对locations列表进行了4 次抽样,对吧?然后我将字典的键设置为 1-10 的数字(“位置”的元素)。这不能保证每个可能的键都与非空列表相关联吗?我错过了什么吗? -
@A.Far:是的,但是在 10 次迭代中的每一次中,您都从其中一个列表中删除了一个元素(在
ne = neighborhd.pop(0)行中)。如果随机数出现正确,您最终会删除其中一个列表的所有四个元素,因此会出现错误。也就是说,随着 while 循环的进行,您正在 修改neighbours的内容。也许那不是你想做的。
标签: python python-3.x