I have a nested list of junctions between cones.
a = [0,1]
b = [2,4]
c = [2,0]
d = [4,3]
e=[a,b,c,d]
I want to write a program that lists eve
Using descriptive names will help make your code more readable.
a = [0,1]
b = [2,4]
c = [2,0]
f = [4,6]
junctions=[a,b,c,d,f]
neighbour_list =[]
If we didn't know in advance what the cones were, we would need to find all the cones in the junctions
# 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]
If you want to only consider cones that have junctions use
##cones = set(cones)
If you want to consider all cones within the range represented in the junctions use
cones = range(min(cones), max(cones) + 1)
It is a bit easier to build the lists if the cone loop is the outer loop because we are trying to find the neighbours for each 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]]
>>>
It seems like neighbour_list is missing some information - you can't readily tell which cone the neighbors are for. You could use zip
to add the information:
>>> print zip(sorted(cones), neighbour_list)
[(0, [1, 2]), (1, [0]), (2, [4, 0]), (3, [4]), (4, [2, 3, 6]), (5, []), (6, [4])]
>>>
Or a slight change in the program could add the info neighbour_list
neighbour_list.append((cone,neighbors))
I recommend using a dictionary instead.
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)
Running it gives:
[[1, 2], [0], [4, 0], [4], [2, 3]]