我有一个锥体之间的连接点的嵌套列表。
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)
我的想法是确定包含锥0,然后是锥1,然后是锥2等的列表,并为每个列提取邻居(即元素[1]或元素[0])并将其附加到neighbour_list。
我收到错误消息:“while element in element” - 类型(int)的参数不可迭代
怎么了?
答案 0 :(得分:0)
我建议改用词典。
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]]
答案 1 :(得分:0)
使用描述性名称有助于使您的代码更易于阅读。
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 循环是外循环,那么构建列表会容易一些,因为我们试图找到每个圆锥的邻居:
# 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]]
>>>
neighbour_list似乎缺少一些信息 - 你不能轻易分辨出邻居所在的锥形区域。您可以使用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
neighbour_list.append((cone,neighbors))