python - 通过切断循环来缩短元组列表?

标签 python list tuples

我有一个生成元组列表的函数,例如:

[(0, 0), (1, 1), (1, 2), (1,3), (2, 4), (3, 5), (4, 5)]

它们用于表示我正在制作的游戏中的图 block (行、列)路径。

我用来生成这些路径的函数并不完美,因为它经常会产生“循环”,如下所示:

[(2, 0), (2, 1), (1, 2), (0, 3), (0, 4), (1, 5), (2, 5), (3, 4), (3, 3),
 (3, 2), (4, 1)]

Image

上面的路径应该是这样的:

[(2, 0), (2, 1), (3, 2), (4, 1)]

Image

这些路径可以包含任意数量的循环,循环可以是任意大小和形状。

所以我的问题是,我如何在 python 中编写一个函数来剪切循环列表并返回一个没有这些循环的新的、更短的列表。

我的尝试如下:

def Cut_Out_Loops(Path):

    NewList = list(Path)
    Cutting = True

    a = 0
    for Cords in Path:
        a += 1

        try:
            for i in range(a + 2, len(Path)):
                if (Path[i][0] == Cords[0] and abs(Path[i][1] - Cords[1]) == 1:
                    NewList = NewList[0:a] + NewList[i:]
                    Path = list(NewList)
                elif Path[i][1] == Cords[1] and abs(Path[i][0] - Cords[0]) == 1:
                    NewList = NewList[0:a] + NewList[i:]
                    Path = list(NewList)
                elif abs(Path[i][0] - Cords[0]) == 1 and abs(Path[i][1] - Cords[1]) == 1:
                    NewList = NewList[0:a] + NewList[i:]
                    Path = list(NewList)
                elif abs(Path[i][1] - Cords[1]) == 1 and abs(Path[i][0] - Cords[0]) == 1:
                    NewList = NewList[0:a] + NewList[i:]
                    Path = list(NewList)
                Cutting = False
        except IndexError:
            Cutting = True

最佳答案

虽然你对“循环”的定义不是很清楚,试试这个

def clean(path):
    path1 = []
    for (x1,y1) in path:
        for (i,(x2,y2)) in enumerate(path1[:-1]):
            if abs(x1-x2) <= 1 and abs(y1-y2) <= 1:
                path1 = path1[:i+1]
                break
        path1.append((x1,y1))
    return path1

它绝对适用于您的示例:

 >>> path = [(2, 0), (2, 1), (1, 2), (0, 3), (0, 4), (1, 5), (2, 5), (3, 4), (3, 3), (3, 2), (4, 1)]
 >>> clean(path)
 [(2, 0), (2, 1), (3, 2), (4, 1)]

也就是说,它只是最直接的蛮力解决方案。复杂度是二次方的。

关于python - 通过切断循环来缩短元组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38862164/

相关文章:

python - 在 python 中,是否可以使用单个命令更新或初始化字典键?

python - 用于 Python 的轻量级 NLP 框架

python - 如何修复 'DataFrame' 对象没有属性 'coalesce'?

python - 将一个数据框的样式结果复制到另一个数据框

c# - 如何在 C# 中复制列表成员?

java - 如何在链表java中的第一个元素前面添加一个点?

jquery 不会将我的列表元素添加到动态注入(inject)的 <ul> 列表中

python - 如何根据原始元组列表中的值创建新的元组列表?

list - Haskell - 我自己的 zip3 函数

python - 如何将元组元素组合到Python中的列表中