Python:list.pop(0)在列表已满时给出索引错误

时间:2016-12-04 13:51:01

标签: python python-3.x pop

所以我试图找回 n 商店的清单,以便他们是邻居,然后,如果有必要,邻居的邻居。以下是用于计算名为位置的此列表的代码。商店的数量从1到10包含在内。

在这种情况下,每家商店都有4个邻居。此关系在名为 neighbors 的字典中随机设置。

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。我意识到结果列表并不总是给我集群,而是从邻居到邻居的路径。这对我正在进行的项目来说很好。

1 个答案:

答案 0 :(得分:0)

我修改了您的代码帮助调试,您可以在下面看到。如果你运行这个,你就会发现当异常被抛出时,邻居会发现这种情况。字典有空列表作为一些值。这意味着&#39; neighborhd&#39;用来自邻居的空列表重新填充&#39;所以仍然是空的。

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)