为什么我的“同时”是函数导致无限循环?

发布于 2025-01-11 14:48:29 字数 250 浏览 0 评论 0原文

我正在尝试创建一个函数来将列表中的所有值加倍。但是,当我运行这个时,我遇到了无限循环。这是我的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒绊 2025-01-18 14:48:29

您不会在 while 循环内的任何时候递增 i,因此您的 i 将始终保持为 0,因为您已初始化它以 0 开头,因此 i 将始终小于列表 ll 的长度,因此会出现无限循环

考虑像这样替换你的方法

def double_values_in_list ( ll ): 
    i = 0
    while ( i < len(ll) ): 
        ll[i] = ll[i] * 2
        print ( "ll[{}] = {}".format( i, ll[i] ) )
        i = i + 1
    return ll

You are not incrementing i at any point inside your while loop so your i will always remain 0 because you initialized it with 0 at start thus i will always be less than the length of your list ll and hence the infinite loop.

consider replacing your method like this

def double_values_in_list ( ll ): 
    i = 0
    while ( i < len(ll) ): 
        ll[i] = ll[i] * 2
        print ( "ll[{}] = {}".format( i, ll[i] ) )
        i = i + 1
    return ll

So要识趣 2025-01-18 14:48:29

因为你的 I 在这个 while 循环中实际上从未增加。如果你真的想这样做,你可以将 ai += 1 添加到你的函数末尾

def double_values_in_list ( ll ): 
    i = 0
    while (i<len(ll) ): 
        ll[i] = ll[i] * 2 
        print ( "ll[{}] = {}".format( i, ll[i] ) )
        i += 1
    return ll

print(double_values_in_list([1, 2]))

但是,这是你不需要采取的很多额外步骤,你可以简单地运行一个 pythonic for 循环来让事情变得更容易

def double_values_in_list (ll): 
    return [x*2 for x in ll]
    

print(double_values_in_list([1, 2]))

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

def double_values_in_list ( ll ): 
    i = 0
    while (i<len(ll) ): 
        ll[i] = ll[i] * 2 
        print ( "ll[{}] = {}".format( i, ll[i] ) )
        i += 1
    return ll

print(double_values_in_list([1, 2]))

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

def double_values_in_list (ll): 
    return [x*2 for x in ll]
    

print(double_values_in_list([1, 2]))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文