这已经让我占据了下午的一半时间......我正在尝试链接嵌套列表的最后一个和第一个元素。我将用一个简单的例子来说明这一点:
input = [(8, 2), (8, 5), (2, 12), (12, 13), (5, 6), (6, 7), (13, 14),
(14, 3), (7, 4), (3, 4)]
result = [(8, 2), (2, 12), (12, 13), (13, 14), (14, 3), (3, 4), (4, 7),
(7, 6), (6, 5), (5, 8)]
我尝试了以下代码:
def ChainNew(L):
R = copy.deepcopy(L)
for pair in R:
pair.reverse()
stop = len(L)
chain = [L.pop(0)]
L = sorted(L)
R = sorted(R)
while len(chain) < stop:
for i, j in zip(L, R):
if i[0] == chain[len(chain)-1][1]:
chain.append((i))
L.remove(i)
R.remove(i[::-1])
break
if j[0] == chain[len(chain)-1][1]:
chain.append((j))
L.remove(j[::-1])
R.remove(j)
break
return chain
但这不仅效率低下,而且也有问题:它似乎没有返回初始列表的所有元素。例如:
L = [[20, 56], [23, 24], [23, 12], [22, 21], [26, 48], [26, 24],
[55, 48], [55, 39], [56, 40], [19, 6], [19, 12], [6, 15],
[40, 39], [21, 57], [14, 15], [14, 16], [57, 50], [45, 9],
[45, 53], [18, 42], [18, 9], [38, 53], [38, 44], [50, 42],
[16, 17], [17, 35], [36, 37], [36, 35], [37, 44]]
return = [[20, 56], [56, 40], [40, 39], [39, 55], [55, 48], [48, 26],
[26, 24], [24, 23], [23, 12], [12, 19], [19, 6], [6, 15],
[15, 14], [14, 16], [16, 17], [17, 35], [35, 36], [36, 37],
[37, 44], [44, 38], [38, 53], [53, 45], [45, 9], [9, 18],
[18, 42], [42, 50], [50, 57]]
必须有一个更简单的方法来做到这一点......
编辑:对不起!我忘了提到每个列表(对)中的整数可以交换。例如 (7, 4) 到 (4, 7)。
基本上,我在每对数字中所拥有的是折线边缘的索引。所有的边一起形成折线。因此,通过“链接”每对数字,我可以以排序的方式获得折线顶点的索引。
再次编辑: 列表 L 的正确结果是:
return = [[22, 21], [21, 57], [57, 50], [50, 42], [42, 18], [18, 9],
[9, 45], [45, 53], [53, 38], [38, 44], [44, 37], [37, 36],
[36, 35], [35, 17], [17, 16], [16, 14], [14, 15], [15, 6],
[6, 19], [19, 12], [12, 23], [23, 24], [24, 26], [26, 48],
[48, 55], [55, 39], [39, 40], [40, 56], [56, 20]]
谢谢!