【问题标题】:Sort a list of tuples using index position of items in another list使用另一个列表中项目的索引位置对元组列表进行排序
【发布时间】:2013-02-02 08:18:51
【问题描述】:

我有一个基本列表。

li = ['fca', 'fc_add', 'fca_2', 'fcadd_2', 'Red_Exis', 'G_Exis', 'P_Exis',
      'fam_1']

并希望使用列表中项目的索引位置对以下元组列表进行排序。

tup= [('G_Exis','abc'), ('fca','210Y'), ('Red_Exis', 107),
      ('fc_add','999 Des ST.')]

我需要最终的排序列表如下所示:

fin_tup = [('fca','210Y'), ('fc_add','999 Des ST.'), ('Red_Exis', 107), 
           ('G_Exis','abc')]

【问题讨论】:

    标签: python list sorting python-2.7 tuples


    【解决方案1】:
    index_dict = {item: index for index, item in enumerate(li)}
    tup.sort(key=lambda t: index_dict[t[0]])
    print(tup)
    

    输出

    [('fca', '210Y'), ('fc_add', '999 Des ST.'), ('Red_Exis', 107),
     ('G_Exis', 'abc')]
    

    或者不排序:

    index_dict = {item: index for index, item in enumerate(li)}
    
    fin_tup = [None]*len(li)
    for t in tup:
        fin_tup[index_dict[t[0]]] = t
    fin_tup = [t for t in fin_tup if t is not None]
    

    【讨论】:

      【解决方案2】:

      一种简单的方法是不实际对其进行排序,而是使用您要排序的键的索引将其存储在字典中作为字典键:

      >>> d ={}
      >>> for i in tup : d[li.index(i[0])] = i
      >>> list(d.values())
      [('fca', '210Y'), ('fc_add', '999 Des ST.'), ('Red_Exis', 107), ('G_Exis', 'abc')]
      

      这是简单的方法,而不是有效的方法。

      【讨论】:

      • 除了 O(n**2) 之外,它还取决于您 d.values() 的顺序,这是不保证的。
      【解决方案3】:

      使用 sort() 的 key 参数。排序的值就是 li 中的索引,所以从每个值中取出第一项,找到 li 中的索引。完成。

      tup.sort(key=lambda item_in_li, trash: li.index(item_in_li))
      

      【讨论】:

        猜你喜欢
        • 2012-09-07
        • 2018-05-14
        • 2021-07-14
        • 1970-01-01
        • 1970-01-01
        • 2019-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多