【问题标题】:python sort list of lists based on inner element AND ignore casepython基于内部元素和忽略大小写的列表排序列表
【发布时间】:2015-03-20 06:49:47
【问题描述】:

假设我在 python 中有以下列表

[ [1,"C"], [2, "D"], [3,"a"], [4,"b"] ]

我想按字母对列表进行排序,这样就可以了

[ [3,"a"], [4,"b"], [1,"C"], [2, "D"] ]

要按内部字符排序,我会使用sorted(unsortedlist, key=itemgetter(1))
要通过忽略大小写进行排序,我会做sorted(unsortedlist, key=str.lower)

如何同时按内部元素排序并忽略大小写?

【问题讨论】:

    标签: python sorting ignore-case


    【解决方案1】:

    这是匿名函数的(罕见)用例之一:

    >>> sorted([[1, 'C'], [2, 'D'], [3, 'a'], [4, 'b']], key=lambda x: x[1].lower())
    [[3, 'a'], [4, 'b'], [1, 'C'], [2, 'D']]
    

    Lambda 通常有点笨拙和不符合 Python 标准,但 unfortunately, there is no "compose" function built-in to python

    【讨论】:

    • 太棒了!像魅力一样工作。谢谢
    【解决方案2】:

    lambda:

    sorted(unsortedlist, key=lambda x: x[1].lower())
    

    或常规函数:

    def my_key(x):
        return x[1].lower()
    
    sorted(unsortedlist, key=my_key)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-18
      • 2019-10-27
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多