gpt4 book ai didi

python - 有没有办法让这段代码更简洁?

转载 作者:行者123 更新时间:2023-11-30 23:49:17 25 4
gpt4 key购买 nike

给定一个项目列表以及从谓词函数到“值”函数的映射,下面的代码将“值”函数应用于满足相应谓词的项目:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com