将序列中的元素组合在序列很重要的Python中

时间:2017-12-07 13:57:45

标签: python list

我有一个2d列表

a = [[[6, 7], [7, 4]],
    [[4, 7], [7, 8], [8, 15]],
    [[3, 19], [15, 3], [19, 12]]]

数字是TSP中的节点名称([6,7]表示从6到7)。 a中的每一行对应于特定日期的游览。我需要制作另一个2d列表,考虑哪些序列:以下是我需要的:

FinalTours = [[6,7,4], 
              [4,7,8,15],
              [15,3,19,12]]

有什么建议吗? 我尝试了下面的代码,但它仅适用于第一天(a的第一行)

FinalTours = [[] for i in range(T)]           
for t in range(T):
    for i in AllTour[t]:
        if t == 0:
            Wakeup = 6
            if i[0] == Wakeup:
                Tour =[]
                Tour.append(Wakeup)
                Tour.append(i[1])
            else:
                if i[0] == Tour[-1]:
                    Tour.append(i[1])
                    FinalTours[t] = Tour

        else:
            Wakeup = Tour[-1] 
            if i[0] == Wakeup:
                Tour =[]
                Tour.append(Wakeup)
                Tour.append(i[1])
            else:
                if i[0] == Tour[-1]:
                    Tour.append(i[1])
                    FinalTours[t] = Tour

1 个答案:

答案 0 :(得分:2)

朴素的方法使用itertools.permutations

强制列表中的路径
from itertools import permutations

def is_path(lst):
    # check if [[a, b], [b, c], [c, d], ...] holds
    return all(x[1] == y[0] for x, y in zip(lst, lst[1:]))

def make_path(lst):
    # find lst permutation that is a path
    for p in permutations(lst, len(lst)):
        if is_path(p):
            return p
    raise ValueError('No Path possible')

def flatten_path(lst):
    # turn [[a, b], [b, c]] into [a, b, c]
    return lst[0][:1] + [x[1] for x in lst]

a = [[[6, 7], [7, 4]],
    [[4, 7], [7, 8], [8, 15]],
    [[3, 19], [15, 3], [19, 12]]]

paths = [flatten_path(make_path(x)) for x in a]
# [[6, 7, 4], [4, 7, 8, 15], [15, 3, 19, 12]]