【问题标题】:Returning organised list from list of tuples从元组列表中返回有组织的列表
【发布时间】:2020-11-24 14:11:02
【问题描述】:

所以我目前正在尝试分析元组列表,并返回一个列表,其中元组中的唯一值作为路径排序(W 导致 X,X 到 Y 等等)。即

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

输入会返回

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

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

【问题讨论】:

  • 是否保证列表形成一个单一的、笔直的路径?如果您将("A", "B") 添加到列表中,输出应该是什么?或("X", "A")("A", "Z")
  • @chepner 给出的列表应该总是有一个干净的路径
  • @jizhihaoSAMA 忽略元组结构并按字典顺序对字符串进行排序。列表[("Z", "Y"), ("X", "W"), ("Y", "X")] 应生成列表["Z", "Y", "X", "W"]

标签: python list tuples list-comprehension


【解决方案1】:
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")]

【讨论】:

  • 我已经测试了你的代码,但是当 input_edges 是 [("Y", "Z"), ("W", "X"), ("X", "Y")] 时,似乎 top_most_source 不是 "W"
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2017-02-15
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    相关资源
    最近更新 更多