【问题标题】:Python lamda function to sort list of tuples based on relationship to previous tuplePython lambda函数根据与前一个元组的关系对元组列表进行排序
【发布时间】:2020-12-17 13:27:29
【问题描述】:

是否可以使用sorted(list, lambda x:..) 对元组列表进行排序,使得下一个元组的第一个值等于前一个元组的第二个值?

list_of_tuples = [("JFK", "DEN"), ("LAX", "ORD"), ("DEN", "SFO"), ("LAS", "LAX"), ("ORD", "ATL"), ("ATL", "JFK"), ("SFO", "LAS")]
Desired_output = [('JFK', 'DEN'), ('DEN', 'SFO'), ('SFO', 'LAS'), ('LAS', 'LAX'), ('LAX', 'ORD'), ('ORD', 'ATL'), ('ATL', 'JFK')]

我知道如何按元组 (sorted(list_of_tuples, key = lambda x: x[0])) 中的任一值进行排序,但是使用 lambda 进行排序并以某种方式引用列表中的前一个值的最佳方法是什么?

【问题讨论】:

    标签: python list sorting tuples


    【解决方案1】:

    sorted() 不可能。但是你可以使用 for 循环来解决它。

    d = dict(list_of_tuples)
    res = [list_of_tuples[0]]
    prev = res[0]
    
    for idx in range(len(list_of_tuples) - 1):
        prev = (prev[1], d[prev[1]])
        res.append(prev)
    print(res)
    

    输出:

    [('JFK', 'DEN'), ('DEN', 'SFO'), ('SFO', 'LAS'), ('LAS', 'LAX'), ('LAX', 'ORD'), ('ORD', 'ATL'), ('ATL', 'JFK')]
    

    【讨论】:

    • list_of_tuples = ((1, 2), (3, 1)) Traceback (most recent call last): KeyError: 2
    • 看到每个元组的第二个值是另一个元组中的第一个元素
    • 在我看来possible...
    【解决方案2】:

    sorted() 无法做到这一点。您正在寻找的是图表中的哈密顿路径

    这里图的顶点是你的元组,如果一个元组的最后一个值与另一个元组的第一个值匹配,则从一个元组到另一个元组有一条有向边。

    但是,如果下一个元组总是只有一个可能的候选者,并且您知道可以从列表中的第一个元素开始,那么问题就简单多了,您不需要任何复杂的 hamiltonian-path算法。

    首先,将列表的元素放入一个高效的数据结构中,以便轻松搜索下一个元组。您可以使用 python 字典。然后,逐个添加元素。

    list_of_tuples = [("JFK", "DEN"), ("LAX", "ORD"), ("DEN", "SFO"), ("LAS", "LAX"), ("ORD", "ATL"), ("ATL", "JFK"), ("SFO", "LAS")]
    
    dict_first = {}
    for pair in list_of_tuples:
      dict_first[pair[0]] = pair
    
    result = [list_of_tuples[0]]
    key = list_of_tuples[0][-1]
    result = []
    while key in dict_first and len(result) < len(list_of_tuples):
      result.append(dict_first[key])
      key = result[-1][-1]
    
    print(result)
    

    输出:

    [('JFK', 'DEN'), ('DEN', 'SFO'), ('SFO', 'LAS'), ('LAS', 'LAX'), ('LAX', 'ORD'), ('ORD', 'ATL'), ('ATL', 'JFK')]
    
    

    【讨论】:

      【解决方案3】:

      试试这个代码,

      list_of_tuples = [("JFK", "DEN"), ("LAX", "ORD"), ("DEN", "SFO"),
                        ("LAS", "LAX"), ("ORD", "ATL"), ("ATL", "JFK"),
                        ("SFO", "LAS")]
      Desired_output=[list_of_tuples[0]]
      for i in range (len(list_of_tuples)):
          for j in  list_of_tuples:
              if Desired_output[i][1]==j[0]:
                  Desired_output.append(j)
      print(Desired_output)
      

      【讨论】:

        猜你喜欢
        • 2021-08-18
        • 1970-01-01
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-21
        • 1970-01-01
        • 2022-01-18
        相关资源
        最近更新 更多