为什么我的“同时”是函数导致无限循环?
我正在尝试创建一个函数来将列表中的所有值加倍。但是,当我运行这个时,我遇到了无限循环。这是我的代码:
def double_values_in_list ( ll ):
i = 0
while ( i < len(ll) ):
ll[i] = ll[i] * 2
print ( "ll[{}] = {}".format( i, ll[i] ) )
return ll
I am trying to create a function to double all values in a list. However, when I run this I get an infinite loop. Here's my code:
def double_values_in_list ( ll ):
i = 0
while ( i < len(ll) ):
ll[i] = ll[i] * 2
print ( "ll[{}] = {}".format( i, ll[i] ) )
return ll
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不会在 while 循环内的任何时候递增
i
,因此您的i
将始终保持为 0,因为您已初始化它以 0 开头,因此i
将始终小于列表ll
的长度,因此会出现无限循环。考虑像这样替换你的方法
You are not incrementing
i
at any point inside your while loop so youri
will always remain 0 because you initialized it with 0 at start thusi
will always be less than the length of your listll
and hence the infinite loop.consider replacing your method like this
因为你的 I 在这个 while 循环中实际上从未增加。如果你真的想这样做,你可以将 ai += 1 添加到你的函数末尾
但是,这是你不需要采取的很多额外步骤,你可以简单地运行一个 pythonic for 循环来让事情变得更容易
Because your I never actually increases in this while loop. If you really want to do it this way you can just add a i += 1 to the end of your function
However, this is a lot of extra steps that you don't need to take, you can simply run a pythonic for loop to make things a lot easier on yourself