如果我有一个像这样的元组列表 [(1, 3), (-6, 3), (1, 7)] 并且我想返回一个像这样的列表 [(7, 1),(1, 3), (3, -6)]。我能做什么?关于如何对元组进行排序的任何想法。基本条件是基于这样一个事实:它们通过与下一个元组中的起始值具有相同的值来“连接”。
我尝试了这段代码,尝试将所有内容放入图表(邻接列表/字典)中,其中每个键都是元组的元素,然后我尝试按照我之前提到的条件进行排列,但它无法正常工作。使用类似于之前给出的输入
列表 = [(1, 3), (-6, 3), (1, 7)]
输出是 [(1, 3), (3, 7), (7, -6)]
而不是 [(7, 1),(1, 3), (3, -6)]
这是我使用的代码
def compoundGraph(compounds):
graph = {}
for tuple in compounds:
if tuple[0] in graph:
graph[tuple[0]].append(tuple[1])
else:
graph[tuple[0]] = [tuple[1]]
return graph
def traverse(graph, start, visited, result):
if start not in visited:
visited.add(start)
result.append(start)
if start in graph:
for neighbor in graph[start]:
traverse(graph, neighbor, visited, result)
def reorderCompounds(tuples_list):
graph = compoundGraph(tuples_list)
result = []
visited = set()
keys_copy = list(graph.keys())
for start in keys_copy:
traverse(graph, start, visited, result)
return [(result[i], result[i+1]) for i in range(len(result)-1)]
list = [(1, 3), (3,7 ),(1,7)]
print(reorderCompounds(list))
如果有人对如何解决这个问题有更优雅或至少正确的想法,我们将不胜感激。
你走在正确的轨道上,但请尝试一下这段代码:
def compoundGraph(compounds):
graph = {}
for tuple in compounds:
if tuple[0] in graph:
graph[tuple[0]].append(tuple[1])
else:
graph[tuple[0]] = [tuple[1]]
return graph
def traverse(graph, start, visited, result):
if start not in visited:
visited.add(start)
if start in graph:
for neighbor in sorted(graph[start], reverse=True):
traverse(graph, neighbor, visited, result)
result.append(start)
def reorderCompounds(tuples_list):
graph = compoundGraph(tuples_list)
result = []
visited = set()
for start in graph.keys():
traverse(graph, start, visited, result)
return [(result[i+1], result[i]) for i in range(len(result)-1)]
# Test the function with your example
input_list = [(1, 3), (-6, 3), (1, 7)]
print(reorderCompounds(input_list))