python dict reg key

来源:互联网 发布:js访问者模式 编辑:程序博客网 时间:2024/06/09 19:40

Dictionary lookup with regular expression as key

I just remembered that I was meant to post that thing here, too. Problem is the following: you want to retrieve all values of a python dictionary whose keys match a certain regular expression. Solution: Just make a custom dictionary class derived from the builtin one:

class redict(dict):    def __init__(self, d):        dict.__init__(self, d)    def __getitem__(self, regex):        r = re.compile(regex)        mkeys = filter(r.match, self.keys())        for i in mkeys:                yield dict.__getitem__(self, i)

With this you can do the following:

>>> keys = ["a", "b", "c", "ab", "ce", "de"]>>> vals = range(0,len(keys))>>> red = redict(zip(keys, vals))>>> for i in red[r"^.e$"]:...     print i...54>>>


flask @app.route('/user/\d+') 的实现:

mkeys = filter(lambda key: key.match(str), self.keys())

sorted(mkeys, cmp=lambda x,y:cmp(len(x), len(y)))

sorted(mkeys, key=lambda x:len(x))


sorted(iterable[cmp[key[reverse]]])

参数解释:

(1)iterable指定要排序的list或者iterable,不用多说;

(2)cmp为函数,指定排序时进行比较的函数,可以指定一个函数或者lambda函数,如:

       students为类对象的list,没个成员有三个域,用sorted进行比较时可以自己定cmp函数,例如这里要通过比较第三个数据成员来排序,代码可以这样写:
      students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
       sorted(students, key=lambda student : student[2])
(3)key为函数,指定取待排序元素的哪一项进行排序,函数用上面的例子来说明,代码如下:
       sorted(students, key=lambda student : student[2]) 
       key指定的lambda函数功能是去元素student的第三个域(即:student[2]),因此sorted排序时,会以students所有元素的第三个域来进行排序。
有了上面的operator.itemgetter函数,也可以用该函数来实现,例如要通过student的第三个域排序,可以这么写:
sorted(students, key=operator.itemgetter(2)) 
sorted函数也可以进行多级排序,例如要根据第二个域和第三个域进行排序,可以这么写:
sorted(students, key=operator.itemgetter(1,2))

0 0
原创粉丝点击