Skip to main content
 首页 » 编程设计

python之在顺序很重要的 Python 中组合列表中的元素

2024年10月01日6TianFang

我有一个二维列表

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

数字是 TSP 中的节点名称([6,7] 表示从 6 到 7)。 a 中的每一行对应于特定日期的一次旅行。我需要制作另一个考虑序列的二维列表:下面是我需要的:

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 

请您参考如下方法:

天真的方法使用 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]]