【发布时间】:2015-11-18 11:23:31
【问题描述】:
在下面的函数中,f1 使用re.findall 并且可以将与dictionary 中的键不匹配的正则表达式选择传递为else ""。
但是,f2 将re.search 与.group 一起使用,并且不能传递与dictionary 中的键不匹配的正则表达式选择。报错:
AttributeError: 'NoneType' 对象没有属性 'group'
dictionary = {"vanilla":"white", "strawberry":"red"}
string = "Yummy chocolate ice cream."
regex = re.compile(r"\b((%s)\S*)\b" %"|".join(dictionary.keys()), re.I)
def f(fruit):
f1 = lambda x: dictionary[regex.findall(x)[0]] if regex.findall(x)[0] in dictionary else ""
f2 = lambda x: dictionary[regex.search(x).group(2)] if regex.search(x).group(2) in dictionary else ""
color_1 = f1(fruit)
color_2 = f2(fruit)
statement = "Buy " + color_2 + " ice cream in the grocery store."
return statement
如何使f2 将不匹配项作为"" 传递而不会出现上述错误,最好使用尽可能少的代码行?请注意,我们必须使用re.search 并且可能使用.group,因此我们无法更改为其他方法。
【问题讨论】:
-
为什么要使用尽可能少的行?为什么不追求简洁而不是可读性?
-
@Cyphase 感谢您的回答。实际上,该函数还执行许多其他操作,因此我希望将其保持在尽可能少的行数以提高可读性。如果您愿意,您还可以将“非简短”版本添加到您的答案中。谢谢!
-
@Cyphase Performance,因为搜索被执行了两次。
-
“为了便于阅读,我想尽可能少写几行”。尽可能少的行数不一定等于可读性。事实上,通常不会。
-
你为什么不告诉我们你当时真正想要做什么,这样我们才能更好地回答? :)
标签: python regex pandas lambda