【问题标题】:Sort a list of tuples without case sensitivity对不区分大小写的元组列表进行排序
【发布时间】:2011-01-30 11:39:42
【问题描述】:

如何在不区分大小写的情况下轻松、高效地对元组列表进行排序?

例如:

[('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)]

排序后应如下所示:

[('a', 5), ('a', 'a'), ('A', 'b'), ('a', 'c')]

常规的字典排序会将 'A' 放在 'a' 之前并产生以下结果:

[('A', 'b'), ('a', 5), ('a', 'a'), ('a', 'c')]

【问题讨论】:

    标签: python sorting tuples case-insensitive


    【解决方案1】:

    Paul McGuires 的简化版作品:

    list_of_tuples.sort(key=lambda t : tuple(t[0].lower()))
    

    (其中 t[0] 引用您要使用的元组元素,在本例中为第一个)

    【讨论】:

      【解决方案2】:

      这是一个使用 Python wiki 文章 (http://wiki.python.org/moin/HowTo/Sorting/) 的“按键排序”部分中说明的装饰器思想的解决方案。

      # Create a list of new tuples whose first element is lowercase
      # version of the original tuple.  I use an extra function to
      # handle tuples which contain non-strings.
      f = lambda x : x.lower() if type(x)==str else x
      deco = [(tuple(f(e) for e in t), t) for t in ex]
      
      # now we can directly sort deco and get the result we want
      deco.sort()
      
      # extract the original tuples in the case-insensitive sorted order
      out = [t for _,t in deco]
      

      【讨论】:

        【解决方案3】:
        list_of_tuples.sort(key=lambda t : tuple(s.lower() if isinstance(s,basestring) else s for s in t))
        

        【讨论】:

        • 不错,紧凑的解决方案。谢谢!
        • 如果您的元组可以包含其他元组或序列结构,那么您可能需要lower_if_possible 解决方案,它包含在一个称为lower_sequence 之类的递归调用程序中,如果它找到一个本身就是它的成员,它就会调用自己一个序列。
        【解决方案4】:

        这样的事情应该可以工作:

        def sort_ci(items):
            def sort_tuple(tuple):
                return ([lower(x) for x in tuple],) + tuple
            temp = [sort_tuple(tuple) for tuple in items]
            temp.sort()
            return [tuple[1:] for tuple in temp]
        

        换句话说,创建一个新列表,其中每个项目是一个由旧元组组成的元组,前缀为相同的元组,每个项目都小写。然后排序。

        如果您的列表很长,这比使用sort 的可选比较函数参数要快一些。

        【讨论】:

          【解决方案5】:

          您可以使用sortkey 参数来定义您希望如何看待每个元素的排序:

          def lower_if_possible(x):
              try:
                  return x.lower()
              except AttributeError:
                  return x
          
          L=[('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)]
          
          L.sort(key=lambda x: map(lower_if_possible,x))
          print(L)
          

          请参阅http://wiki.python.org/moin/HowTo/Sorting,了解如何使用key

          【讨论】:

          • 酷,我试图弄清楚如何在这种情况下使用 key 并且我没有想到使用 map()。谢谢!
          猜你喜欢
          • 1970-01-01
          • 2013-02-11
          • 1970-01-01
          • 2013-04-17
          • 1970-01-01
          • 2019-02-06
          • 1970-01-01
          相关资源
          最近更新 更多