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



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

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

因为输入将返回

["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. 多个"根"节点[("A", "C"), ("B", "C")]
  2. 一个节点有多个目标[("A", "B"), ("A", "C")]

这可能不是最蟒蛇的方式,但你可以这样做:

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']

最新更新