解决以下问题的最快方法是什么? 我将基于常见的头部或尾部加入几个列表
input = ([5,6,7], [1,2,3], [3,4,5], [8, 9])
output = [1, 2, 3, 4, 5, 6, 7]
答案 0 :(得分:1)
>>> def chain(inp):
d = {}
for i in inp:
d[i[0]] = i[:], i[-1]
l, n = d.pop(min(d))
while True:
lt, n = d.pop(n, [None, None])
if n is None:
if len(d) == len(inp) - 1:
l, n = d.pop(min(d))
continue
break
l += lt[1:]
return l
>>> chain(input)
[1, 2, 3, 4, 5, 6, 7]
>>> chain(([5,6,7], [1,2,10], [3,4,5], [8, 9]))
[3, 4, 5, 6, 7]