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
- python dict reg key
- python dict 按key排序
- python dict.get()和dict['key']的使用
- python dict 遍历key效率问题
- 【python】判断key是否存在于dict
- python--用户自定义类对象作为dict的key
- python dict order by key 字典关键字排序
- python字符编码导致dict中key不同
- python迭代dict的key和value
- python 对key为时间的dict排序
- python 判断dict中是否含有某个key
- Python 读Dict数据的方法,解决key 不在dict的问题,get()函数,setdefault()函数
- Python基础—— dict.get() 与 dict['key'] 的区别
- python中的key-value结构的dict和set的key值选择
- python dict
- python dict
- python dict
- Python---dict
- 阿里笔试题-------ArrayList和LinkedList的区别,ArrayList与Vector区别
- 编码基本知识
- 软件经济学五:创建高效率的团队
- 如果需要统一设置编码
- flume学习
- python dict reg key
- 微软100题-天天做-第32题
- java!
- mysql笔记-- mysql命令札记8 --MySql 数据表类型
- JAVA设计模式之策略模式(2)商场打折
- 2014_3_29_周赛 马腿上的最短路
- ThinkpadX200 空只电池充电阀值
- NOIP2000计算器的改良
- 2014_3_29_周赛 倒水