gpt4 book ai didi

python - 在 Python 中创建渐进式列表迭代

转载 作者:行者123 更新时间:2023-11-28 18:41:21 26 4
gpt4 key购买 nike

我有一个包含线(几何)的列表。这些线组成多种形状(方形、矩形等)。然而,它们被分解了,我正在想办法将它们按形状分组到单独的列表中。例如,如果我的列表包含 8 行,并且我知道它们有两个矩形形状,我想创建两组,每组四行。现在,我可以在每一行中查询 StartPoint() 和 EndPoint()。我正在考虑设置一个循环遍历列表的循环。选择列表中的第一行。获取它的终点,然后检查它是否等于列表中其余行的任何起点。如果是,则将该行与第一行一起添加到列表中。然后拿第二条线做同样的事情,直到线的起点等于最后一行的终点,第一条线的起点等于它的终点。我该怎么做?

lines = [line1, line2, line3, line4, line5, line6, line7] #that means i have a square and a triangle
for i in lines:
shape1.append(lines[0])
sPoint = lines[0].StartPoint()
ePoint = lines[0].EndPoint()
if i.StartPoint() == ePoint:
shape1.append(i)

我不确定如何自动创建“形状”列表以及如何打破循环,以免我在圈子里跑。

任何帮助将不胜感激。谢谢,

最佳答案

如果您花一些时间抽象您的问题,您会发现您实际上只是在做图形。

图由顶点和边组成。 Vertices 是您的起点和终点。

我写了一段代码,一旦您了解如何将数据转换为建议的格式,它应该可以帮助您解决问题。

注释:

我建议您在阅读我的代码时阅读内置类型 set()

vertices = set(['A', 'C', 'B', 'E', 'D', 'G', 'F'])

#think of this as Line1.StartPoint()='A' Line1.EndPoint()='B' ...
edges = {'A': 'B',
'B': 'C',
'C': 'D',
'D': 'A',
'E': 'F',
'F': 'G',
'G': 'E'}

shapes = set()

#Check if we tested all edges
while len(vertices) is not 0:
next = vertices.pop()
shape = set()
while next not in shape:
shape.add(next)
next = edges[next]
shapes.add(frozenset(shape))

print shapes

结果:

>>set([frozenset(['A', 'C', 'B', 'D']), frozenset(['E', 'G', 'F'])])

编辑:主要加速是可能的,但为了简单起见,省略了。

关于python - 在 Python 中创建渐进式列表迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25678602/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com