如何迭代列表并将属性替换为具有相同属性的另一个列表Python

问题描述 投票:0回答:1

我想编写一些代码,对于列表“路径”,检查每条路径,并检查路径内的每条边,如果边中的一个顶点等于循环中的顶点,则会将该循环添加到小路。这只是一个示例,但对于一条路径来说,如果有意义的话,该路径的任何点都可能有多个连接循环。我编写的代码将循环添加两次,并添加到它自己的列表中,而不是单独的边中。

paths = [
    [[1, 2]],
    [[1, 2], [2, 3], [3, 4]],
    [[1, 2], [2, 3], [3, 8], [8, 9], [9, 10]]
    ]

cycles = [
    [[10, 11], [11, 12], [12, 10]],
    [[4, 5], [5, 6], [6, 7], [7, 4]]
    ]

for current_path in paths:
    for path_edge in current_path:
        for path_vertice in path_edge:
            for cycles_i in cycles:
                for cycles_edge in cycles_i:
                    for cycles_vertice in cycles_edge:
                        if path_vertice == cycles_vertice:
                            path_edge.append(cycles_i)

# output I get
paths = [
    [[1, 2]],
    [[1, 2], [2, 3], [3, 4, [[4, 5], [5, 6], [6, 7], [7, 4]], [[4, 5], [5, 6], [6, 7], [7, 4]]]],
    [[1, 2], [2, 3], [3, 8], [8, 9], [9, 10, [[10, 11], [11, 12], [12, 10]], [[10, 11], [11, 12], [12, 10]]]]
    ]
# output I want
paths = [
    [[1, 2]],
    [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 4]],
    [[1, 2], [2, 3], [3, 8], [8, 9], [9, 10], [10, 11], [11, 12], [12, 10]]
    ]
python graph edges
1个回答
0
投票

这是一个可能的解决方案:

result = []
for path in paths:
    new_path = []
    for edge_p in path:
        j, i = next(
            ((j, i)
             for j, cycle in enumerate(cycles)
             for i, edge_c in enumerate(cycle)
             if edge_c[0] == edge_p[1]),
            (None, None),
        )
        new_path.append(edge_p)
        if j is not None:
            new_path += cycles[j][i:] + cycles[j][:i]
    result.append(new_path)       

如果您使用您提供的数据尝试此算法,您将得到:

>>> result
[[[1, 2]],
 [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 4]],
 [[1, 2], [2, 3], [3, 8], [8, 9], [9, 10], [10, 11], [11, 12], [12, 10]]]
© www.soinside.com 2019 - 2024. All rights reserved.