Python 对列表进行排序,使列表的最后一个元素等于下一个列表的第一个元素

Python 对列表进行排序,使列表的最后一个元素等于下一个列表的第一个元素,python,Python,我有一个列表,它是 my_list=[[9, 10, 1], [1, 7, 5, 6, 11], [0, 4], [4, 2, 9]] 我想对该列表进行排序,使其如下所示: result=[[0, 4], [4, 2, 9],[9, 10, 1], [1, 7, 5, 6, 11]] 条件是: 1.列表应以包含零的元素开始。 2.列表的最后一个元素应与下一个列表的第一个元素相同,依此类推。 3.子列表中的元素应与原始列表的顺序相同 谢谢。这不是一个很好的实现,但它可以工作: my_list=

我有一个列表,它是

my_list=[[9, 10, 1], [1, 7, 5, 6, 11], [0, 4], [4, 2, 9]]
我想对该列表进行排序,使其如下所示:

result=[[0, 4], [4, 2, 9],[9, 10, 1], [1, 7, 5, 6, 11]]
条件是: 1.列表应以包含零的元素开始。 2.列表的最后一个元素应与下一个列表的第一个元素相同,依此类推。 3.子列表中的元素应与原始列表的顺序相同


谢谢。

这不是一个很好的实现,但它可以工作:

my_list=[[9, 10, 1], [1, 7, 5, 6, 11], [0, 4], [4, 2, 9]]

new_list = []
index = 0
while my_list:
    index = [item[0] for item in my_list].index(index)
    item = my_list[index]
    del my_list[index]
    new_list.append(item)
    index = item[-1]
print(new_list)

当未找到符合条件的子列表时,将引发
ValueError
如果列表中的每个排列都是有效排列,则可以检查它们。也许可以编写一个更有效的算法,但这个算法并不假设存在唯一可能的解决方案

from itertools import permutations

my_list=[[9, 10, 1], [1, 7, 5, 6, 11], [0, 4], [4, 2, 9]]

def sortCheck(a):
    if a[0][0] != 0:
        return False

    for i in range(0, len(a) - 1):
        if a[i][-1] != a[i+1][0]:
            return False
    return True

result_list = []

for permutation in permutations(my_list):
    if sortCheck(permutation):
        result_list.append(list(permutation))

快速解决方案是构建一个dict,根据第一个元素将数字映射到子列表:

dct = {sublist[0]: sublist for sublist in my_list}
# {0: [0, 4], 9: [9, 10, 1], 1: [1, 7, 5, 6, 11], 4: [4, 2, 9]}
然后,从数字0开始,查找需要添加到dict中的下一个子列表:

result = []
num = 0  # start with the sublist where the first element is 0
while True:
    try:
        # find the sublist that has `num` as the first element
        sublist = dct[num]
    except KeyError:
        # if there is no such sublist, we're done
        break

    # add the sublist to the result and update `num`
    result.append(sublist)
    num = sublist[-1]
这在线性
O(n)
时间内运行,并给出预期结果:

[[0, 4], [4, 2, 9], [9, 10, 1], [1, 7, 5, 6, 11]]
def排序列表(列表)
哈希={}
列出每个do |值|
哈希[值[0]]=值
结束
键=0
排序=[]
列出每一个do | k|
item=散列[键到i]
键=项[-1]

你能保证这个条件是可能的吗?请说明你想要什么。如果没有这样的订单呢?(例如,
[[0,1],[2,3]]
)如果有多个可能的订单怎么办?像
[[0,0],[0,1,0]]
?是的,这样的条件总是可能的,子列表中的顺序必须与原始列表相同。这不是问题;这只是对代码的请求。如果有多个子列表以同一元素开头,则只有最后一个子列表将存储在
dct
中,而不是OP所要求的for@sciroccoricsOP已经证实了这是不可能的。你的解决方案比我的更漂亮、更有效(和/但更具体),但称之为“智能解决方案”意味着其他解决方案“不智能”,我认为这有点粗鲁
    def sortList(list)
      hash = {}
      list.each do |value|
        hash[value[0]] = value
      end
      key = 0
      sorted = []
      list.each do |k|
        item = hash[key.to_i]
        key = item[-1]
        sorted << item
      end
      sorted
    end