Dict.setdefault插入到列表中的排序

时间:2018-08-23 09:32:11

标签: python insertion-sort

我想知道是否有一种方法可以使用类似lambda的样式将其追加到已排序的字典的列表字段中。

示例:

Ext.define('SomeList', {

  extend: 'Ext.grid.Panel',
  mixins: {
    field: 'Ext.form.field.Field'
  },
  xtype: 'myXType',
  requires: [...],

  columns: [
    {
        header: 'ID',
        dataIndex: 'id',
        width: 50
    },
    {
        header: 'Checked?',
        xtype: 'checkcolumn',
        dataIndex: 'checked',
        width: 120,
        listeners: {
            checkchange: function( component, rowIndex, checked, eOpts ) {
                console.log('checkchange', component, rowIndex, checked, eOpts);
                // how to access the table's column record here?
            },
        },
    }
],
...

是否有一种使用a = {} a.setdefault("foo", []).append(2) a.setdefault("foo", []).append(1) {'foo': [2, 1]} 的方式insert in sorted order的方式,所以我以后不需要调用sort了?

3 个答案:

答案 0 :(得分:2)

您需要的只是在Pythons标准库中:

import bisect
from collections import defaultdict


def add(dd, key, value):
    bisect.insort_left(dd[key], value)


a = defaultdict(list)
add(a, "foo", 3)
add(a, "foo", 2)
add(a, "foo", 1)
add(a, "foo", 3)
add(a, "foo", 2)
add(a, "foo", 1)

assert a["foo"] == sorted(a["foo"])
print(a)

如果您想要lambda:

add = lambda dd, key, value: bisect.insort_left(dd[key], value)

就性能而言,事后使用sort比运行bisect.insort_left更快。在这两种情况下,运行时复杂度均为 O(n log n),但函数调用开销将导致不同的绝对运行时间。

答案 1 :(得分:1)

您可以改用collections.defaultdict,并使用某些SortedList实现(随pip install sortedcontainers下载,但还有其他实现):

import collections
from sortedcontainers import SortedList

a = collections.defaultdict(SortedList)
a["foo"].add(2)
a["foo"].add(1)
print(a)

结果:

defaultdict(<class 'sortedcontainers.sortedlist.SortedList'>, {'foo': SortedList([1, 2])})

如果要重构的代码很多,可以用add覆盖append

请注意,它也可以与setdefault一起使用,但是比较麻烦:

a = {}
a.setdefault("foo", SortedList()).add(2)
a.setdefault("foo", SortedList()).add(1)

(并且在许多元素上执行此操作的缺点是创建一个SortedList()对象,以防万一密钥不存在)

答案 2 :(得分:0)

尽管可以执行此操作,但需要使用辅助功能:

def list_append(lst, item):
    lst.append(item)
    return lst

a = {}
list_append(a.setdefault("foo", []), 2).sort()
list_append(a.setdefault("foo", []), 1).sort()

但是我绝对会建议您尝试其他数据结构,例如heapq

相关问题