【问题标题】:Sorting lists based on a particular element - Python基于特定元素对列表进行排序 - Python
【发布时间】:2015-03-06 12:25:17
【问题描述】:

如何根据 Python 中列表的第一个元素对列表进行排序?

>>> list01 = (['a','b','c'],['b','a','d'],['d','e','c'],['a','f','d'])
>>> map(sorted, list01)
[['a', 'b', 'c'], ['a', 'b', 'd'], ['c', 'd', 'e'], ['a', 'd', 'f']]
>>> sorted(map(sorted, list01))
[['a', 'b', 'c'], ['a', 'b', 'd'], ['a', 'd', 'f'], ['c', 'd', 'e']]

【问题讨论】:

  • 这看起来可能对你有帮助:stackoverflow.com/q/280222/2740086
  • 默认情况下,sort方法按索引顺序排序,从零或第一个元素开始。
  • 如果你只对第一个元素进行排序,那么像[['a','z','z'],['a','a',b']] 这样的东西会自动排序(因为 Python 的排序是稳定的。)这是你想要的吗?

标签: python list sorting


【解决方案1】:

Python 的 sorted() 可以接收一个函数来排序。 如果要按每个子列表中的第一个元素排序,可以使用以下内容:

>>> lst = [[2, 3], [1, 2]]
>>> sorted(lst, key=lambda x: x[0])
[[1, 2], [2, 3]]

有关 sorted() 的更多信息,请参阅official docs

【讨论】:

    【解决方案2】:
    from operator import itemgetter    
    sorted(list01, key=itemgetter(0))
    

    【讨论】:

      【解决方案3】:
      >>> sorted(list01, key=lambda l: l[0])
      [['a', 'b', 'c'], ['a', 'f', 'd'], ['b', 'a', 'd'], ['d', 'e', 'c']]
      

      这是你的意思吗?

      【讨论】:

        【解决方案4】:

        除了将key 函数传递给sorted(如前面的答案所示)之外,您还可以在Python2 中将cmp(比较)函数传递给它,如下所示:

        sorted(list01, cmp=lambda b, a: cmp(b[0], a[0]))
        

        上述表达式的输出与使用key函数的输出相同。

        尽管他们已经从sortedhttps://docs.python.org/3.3/library/functions.html#sorted 中删除了 Python3 中的cmp 参数,并且使用key 函数是唯一的选择。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-29
          相关资源
          最近更新 更多