gpt4 book ai didi

python - 基于公共(public)头或尾连接列表

转载 作者:太空宇宙 更新时间:2023-11-03 19:38:11 25 4
gpt4 key购买 nike

解决以下问题最快的方法是什么我将根据共同的头部或尾部加入多个列表

input = ([5,6,7], [1,2,3], [3,4,5], [8, 9])
output = [1, 2, 3, 4, 5, 6, 7]

最佳答案

>>> 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]

关于python - 基于公共(public)头或尾连接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2296406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com