提问人:Pat Loranger 提问时间:7/20/2023 最后编辑:ifly6Pat Loranger 更新时间:10/25/2023 访问量:32
在 Python 中简化 if(condition):将 True 返回到一行返回语句更改结果
Simplifying if(condition): return True to one line return statement changes results in Python
问:
我不明白为什么下面写的两种方法性能不同。如果能深入了解为什么 xyz_there() 中的简化语句在此测试用例中失败,我们将不胜感激!
str = "abcxyz"
def xyz_there(str):
for i in range(len(str)):
return (str[i:i+3] == 'xyz' and str[i-1] != '.')
return False
def xyz_there2(str):
for i in range(len(str)):
if str[i:i+3] == 'xyz' and str[i-1] != '.':
return True
return False
print(xyz_there(str))
print(xyz_there2(str))
我一直认为 return(condition) 是编写该表达式的最有效方式。我知道 find() 和 count() 等函数也可以用来解决这个问题。
答:
1赞
Lex-2008
7/20/2023
#1
这两个函数的区别在于,在第二个函数中,语句在 里面,所以只有当条件为真时才会执行。如果不是 true - 循环继续到下一个值 。xyz_there2
return True
if
i
但是,在第一个函数中,该语句不在任何语句中,因此它在循环的第一次迭代时执行,从而返回值。之后,函数退出,循环没有机会迭代到下一个值。xyz_there
return
if
False
i
换言之,函数在第一次循环迭代时返回,当 .While 迭代直到 ,并返回 .xyz_there
False
i==0
xyz_there2
i==3
True
0赞
eshirvana
7/20/2023
#2
你的第一个函数等效于这个,它返回 Flase :
def xyz_there(str):
return (str[0:3] == 'xyz' and str[-1] != '.')
因为你没有遍历字符串中的所有字符,所以你只是在单词的前 3 个字母上做出决定并返回它
评论
i = 0