I have a series of lists, and I want to combine them in a larger nested list. However, I want to order them in a certain way. I want the first sub-list to be the one whose first element is zero. Then i want the second sub-list to be the one whose first element is the same as the LAST element of the previous list.
For example, here's four sub-lists;
[0, 3], [7, 0], [3, 8], [8, 7]
I want to end up with this;
[[0, 3], [3, 8], [8, 7], [7,0]]
I can't for the life of me see the code logic in my head that would achieve this for me.
Can anyone help please?
CodePudding user response:
I think of your list as being a collection of links which are to be arranged into a chain. Here is an approach which uses @quanrama 's idea of a dictionary keyed by the first element of that link:
links = [[0, 3], [7, 0], [3, 8], [8, 7]]
d = {link[0]:link for link in links}
chain = []
i = min(d)
while d:
link = d[i]
chain.append(link)
del d[i]
i = link[1]
print(chain) #[[0, 3], [3, 8], [8, 7], [7, 0]]
CodePudding user response:
Another approach with a generator function:
links = [[0, 3], [7, 0], [3, 8], [8, 7]]
def get_path(links, *, start=0, end=0):
linkmap = dict(links)
key = start
while True:
link = linkmap[key]
yield [key,link]
key = link
if link == end:
break
print(list(get_path(links)))
print(list(get_path(links,start=3,end=3)))
# [[0, 3], [3, 8], [8, 7], [7, 0]]
# [[3, 8], [8, 7], [7, 0], [0, 3]]
CodePudding user response:
You can try something like this:
source = [[0, 3], [7, 0], [3, 8], [8, 7]]
# Start at 0
last_val = 0
# this will be the output
l = []
while len(l)==0 or last_val!=0:
# Find the first value where the first element is last_val
l.append(next(i for i in source if i[0]==last_val))
# set last val to the second element of the list
last_val = l[-1][1]
print(l)