从元组列表返回有组织的列表

Returning organised list from list of tuples

所以我目前正在尝试分析一个元组列表,return 一个列表,其中元组中的唯一值按路径排序(W 指向 X,X 指向 Y,依此类推)。即

[("Y", "Z"), ("W", "X"), ("X", "Y")] 

因为输入会 return

["W", "X", "Y", "Z"]

我可以使用 set(j for i in list for j in i) 来获取唯一元素,但我很难根据路径进行排序。

edges: Dict[str, str] = {}  # Map source to destination
reverse_edges: Dict[str, str] = {}

for (source, dest) in input_edges:
  edges[source] = dest
  reverse_edges[dest] = source

要按顺序获取路径...

path = []

# Pick a node to start from
start = input_edges[0][0]

# Go from the start back to the top of the path
current_node = reverse_edges[start]
while current_node:
  path.insert(0, current_node)
  current_node = reverse_edges.get(current_node)

# Go from the start to the end of the path
current_node = start
while current_node:
  path.append(current_node)
  current_node = edges.get(current_node)

print(path)  # ['W', 'X', 'Y', 'Z']

这并不能处理人们可以想象到的各种边缘情况,但它应该足以让您入门! 注意事项...

  1. 多个'root'节点[("A", "C"), ("B", "C")]
  2. 一个节点有多个目的地[("A", "B"), ("A", "C")]

这可能不是最符合 Python 风格的方法,但您可以这样做:

tuple_list=[("Y", "Z"), ("W", "X"), ("X", "Y"),('B','W'),('A','B')]
result_list=[]

for x,y in sorted(tuple_list):
    if x in result_list:
        ind_x=result_list.index(x)
        result_list.insert(ind_x+1,y)
    elif y in result_list:
        ind_y=result_list.index(y)
        result_list.insert(ind_y,x)
    else:
        result_list.extend([x,y])

结果:

['A', 'B', 'W', 'X', 'Y', 'Z']