0

我有一个顶点列表和它们之间的长度。我想创建一个函数,通过搜索列表来查找列表中两个顶点之间的距离。

该列表将类似于:

lengths = [[X, Y, length], [X, Z, length], [Y, Z, length], etc]

假设顶点是 X 和 Y 我可以使用 X,Y 索引列表以找到 X 和 Y 之间的长度吗?

目前我正在这样做:

def find_sides(X, Y, lengths):
    for a in lengths:
        if a[0] == X and a[1] == Y:
            length = a[2]
    return length

但随着长度列表的增加,这可能需要时间。

谢谢

4

1 回答 1

2

You can use a dictionary:

lengths = {(X, Y): length, (X, Z): length, (Y, Z): length, ...}

Then it's just a matter of indexing the dictionary:

length = lengths[(X, Y)]

You can transform your current list to the proposed format with a dictionary comprehension:

lengthDict = {(a, b): c for [a, b, c] in lengthList}
于 2013-05-07T15:36:16.047 回答