gpt4 book ai didi

python - python 是否缓存或重新计算 while 循环操作上的函数调用

转载 作者:行者123 更新时间:2023-12-02 19:37:39 26 4
gpt4 key购买 nike

鉴于以下情况:

s = '1234567'
i = 0
while (i < len(s)):
i += 1

Python 是否在每个循环中重新计算 len(s),还是只计算一次?换句话说,我应该将上面的 len(s) 移动到循环上方的变量中,还是放在原来的位置就可以了?

最佳答案

https://docs.python.org/3/reference/compound_stmts.html#the-while-statement

while_stmt ::=  "while" assignment_expression ":" suite
["else" ":" suite]

This repeatedly tests the expression and, if it is true, executes the first suite;

通过将 len 替换为客户长度函数,您可以验证行为。

>>> def mylen(s):
... print('mylen called')
... return len(s)
...
>>> s = '1234567'
>>> i = 0
>>> while i < mylen(s):
... i += 1
...
mylen called
mylen called
mylen called
mylen called
mylen called
mylen called
mylen called
mylen called

顺便说一句,如果您想顺序迭代序列(在本例中为字符串),为什么不使用简单的 for 循环。

如果确实需要使用索引,可以使用enumerate:

>>> for i, character in enumerate(s):
... print(i, character)
...
0 1
1 2
2 3
3 4
4 5
5 6
6 7

关于python - python 是否缓存或重新计算 while 循环操作上的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60824952/

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