很难把每个犯人的邻居联系起来

2024-09-27 19:27:55 发布

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

我有一个锥体间连接的嵌套列表。你知道吗

a = [0,1]
b = [2,4]
c = [2,0]
d = [4,3]

e=[a,b,c,d]

我想写一个程序,列出锥0的每个邻居,锥1的每个邻居。。。 我希望输出为[[1,2],[0],[0,4],[4],[2,3]]

我做了以下工作:

neighbour_list =[]
cone = 0

for element in e:

   while cone in element:

      if cone == element[0]:
        neighbour = element[1]
        neighbour_list.append(neighbour)

      else:
        neighbour = element[0]
        neighbour_list.append(neighbour)


      cone = cone + 1
 print(neighbour_list)

我的想法是识别包含cone 0、cone 1、cone 2等的列表,然后为每个列表提取邻居(即元素[1]或元素[0]),并将其附加到邻居列表中。你知道吗

我得到错误消息:“while cone in element”-类型为(int)not iterable的参数

怎么了?你知道吗


Tags: in程序元素列表forifelementelse
2条回答

我建议改用字典。你知道吗

a = [0, 1]
b = [2, 4]
c = [2, 0]
d = [4, 3]

e = [a, b, c, d]
neighbour_list = {}

for x, y in e:
    neighbour_list.setdefault(x, [])
    neighbour_list[x].append(y)
    neighbour_list.setdefault(y, [])
    neighbour_list[y].append(x)
neighbour_list = list(neighbour_list.values())
print(neighbour_list)

运行它可以:

[[1, 2], [0], [4, 0], [4], [2, 3]]

使用描述性名称将有助于提高代码的可读性。你知道吗

a = [0,1]
b = [2,4]
c = [2,0]
f = [4,6]
junctions=[a,b,c,d,f]
neighbour_list =[]

如果我们事先不知道锥体是什么,我们就需要找到连接处的所有锥体

# find all the cones in the junctions
cones = list()
for junction in junctions:
    for cone in junction:
        cones.append(cone)
# The previous could be replaced with a list comprehension
# cones = [cone for junction in junctions for cone in junction]

如果你只想考虑有连接点的锥体

##cones = set(cones)

如果要考虑交叉点中表示的范围内的所有圆锥体,请使用

cones = range(min(cones), max(cones) + 1)

如果cone循环是外循环,则构建列表会更容易一些,因为我们正试图找到每个cone的邻居:

# for each cone look through the junctions to find neighbors
for cone in sorted(cones):    #search for neighbors from the smallest to the largest cone
    neighbors = list()    #make a new list for each cone
    for junction in junctions:
        if junction[0] == cone:
            neighbors.append(junction[1])
        elif junction[1] == cone:
            neighbors.append(junction[0])
    neighbour_list.append(neighbors)

>>> print neighbour_list
[[1, 2], [0], [4, 0], [4], [2, 3, 6], [], [4]]
>>> 

似乎邻居的名单遗漏了一些信息-你不能轻易地分辨出邻居是为哪个圆锥。您可以使用zip添加信息:

>>> print zip(sorted(cones), neighbour_list)
[(0, [1, 2]), (1, [0]), (2, [4, 0]), (3, [4]), (4, [2, 3, 6]), (5, []), (6, [4])]
>>> 

或者在程序中稍加修改就可以添加信息列表

neighbour_list.append((cone,neighbors))

相关问题 更多 >

    热门问题