def parse_shot_success(string):
"""
Determine if the shot was successful.
Input:
string: a string to be analyzed
Returns:
"scores" or "misses" or "not a shot" based on
the shot success.
"""
pp = re.compile("(scores|misses|blocks)")
match = pp.search(string)
if match.group(1) == "scores":
return "scores"
elif match.group(1) == ("blocks|misses"):
return "misses"
else:
return "not a shot"
嗨,我想回复"未命中"或"得分"基于玩家是否在字符串中得分或错过,以便parse_shot_success("Johnson blocks Lebron's shot")
将返回未命中。我想我必须使用for loop
,但我不确定如何将其合并到我的代码中。你能帮我谢谢。
答案 0 :(得分:1)
如果你真的想要使用正则表达式:
def parse_shot_success(string):
pp = re.compile("(scores|misses|blocks)")
match = pp.search(string)
if not match:
# https://docs.python.org/dev/library/re.html#re.search
# "Return None if no position in the string matches the pattern"
return "not a shot"
elif match.group(1) == "scores":
return "scores"
elif match.group(1) in ("blocks", "misses"):
return "misses"
else:
raise AssertionError
但是这个问题可以通过其他方式轻松解决:
def parse_shot_success(string):
if 'scores' in string:
return 'scores'
elif 'blocks' in string or 'misses' in string:
return 'misses'
else:
return 'not a shot'
或者:
def parse_shot_success(string):
words = [
# (word, return value)
('scores', 'scores'),
('blocks', 'misses'),
('misses', 'misses'),
]
for word, result in words:
if word in string:
return result
return 'not a shot'
您有一些未考虑的问题:
"SCORE"
(大写)?