作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
给定一个项目列表以及从谓词函数到“值”函数的映射,下面的代码将“值”函数应用于满足相应谓词的项目:
my_re0 = re.compile(r'^([a-z]+)$')
my_re1 = re.compile(r'^([0-9]+)$')
my_map = [
(my_re0.search, lambda x: x),
(my_re1.search, lambda x: x),
]<br/>
for x in ['abc','123','a1']:
for p, f in my_map:
v = p(x)
if v:
print f(v.groups())
break
有没有办法用一条语句来表达同样的意思?
如果我不必将谓词返回的值传递给“value”函数,那么我可以这样做
for x in ['abc','123','a1']:
print next((f(x) for p, f in my_map if p(x)), None)
可以对上面的代码做类似的事情吗?我知道,也许保留这些嵌套的 for 循环会更好,但我只是好奇这是否可能。
最佳答案
比 Nate 的简洁一点;-)
from itertools import product
comb = product(my_map, ['abc','123','a1'])
mapped = ((p(x),f) for (p,f),x in comb)
groups = (f(v.groups()) for v,f in mapped if v)
print next(groups), list(groups) # first match and the rest of them
关于python - 有没有办法让这段代码更简洁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7720130/
我是一名优秀的程序员,十分优秀!