【问题标题】:Create sorted list while creation创建时创建排序列表
【发布时间】:2013-08-22 08:19:59
【问题描述】:

我们可以在创建列表本身的同时创建排序列表吗?

或者

是否有任何其他数据结构可以在创建时按排序顺序放置值?

list = []
list.append("cde")
list.append("abc")
list.append("xyz")  # append element in sorted order itself 

我熟悉

list.sort()  #or
list = sorted(list)

【问题讨论】:

标签: python list data-structures


【解决方案1】:

您可以使用bisect 在序列中执行有序插入。

bisect.bisect_left(a, x, lo=0, hi=len(a))

a 中定位 x 的插入点以保持排序顺序。 [...] 假设 a 已经排序,返回值适合用作list.insert() 的第一个参数。

【讨论】:

    【解决方案2】:

    您可以使用OrderedDict 创建有序字典。 你可以从这里导入OrderedDict from collections import OrderedDict

    【讨论】:

      【解决方案3】:

      你可以使用heapq方法

      >>> list = []
      >>> import heapq
      >>> heapq.heappush(list, "cde")
      >>> heapq.heappush(list, "abc")
      >>> heapq.heappush(list, "xyz")
      >>> heapq.nsmallest(3, list)
      ['abc', 'cde', 'xyz']
      

      它实际上并没有排序,但你可以执行你需要的排序操作

      【讨论】:

        【解决方案4】:

        我发现这很有用,

        class SList(list):
            def append(self, data):
                super(SList, self).append(data)
                super(SList, self).sort()
        
        
        slist = SList()
        slist.append("cde")
        slist.append("abc")
        slist.append("xyz")
        print slist
        

        同样我们可以重写其他方法来保持列表状态排序

        【讨论】:

          猜你喜欢
          • 2015-07-11
          • 2018-06-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-01
          • 2016-06-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多