【问题标题】:Multiple python append functions in while loop crashingwhile循环崩溃中的多个python附加函数
【发布时间】:2020-03-29 16:29:56
【问题描述】:

尝试通过依次附加三个较小列表中的项目来打印复合列表:

def final_xyz_lister():
    global final_xyz_list
    final_xyz_list = []
    step=0
    while step==0:
        final_xyz_list.append(carbon_final_list[step]) 
        final_xyz_list.append(oxygen_final_list[step]) 
        final_xyz_list.append(hydrogen_final_list[step]) 
        step=+1
    while 0 < step < 50:   
        final_xyz_list.append(carbon_final_list[step]) 
        final_xyz_list.append(oxygen_final_list[step]) 
        final_xyz_list.append(hydrogen_final_list[step]) 
        step=+1
    else:
        pass   

如果我注释掉第二个 while 循环,则列表的第一个元素按预期打印在列表中,但引入第二个 while 循环会导致 MemoryError。

【问题讨论】:

  • 你能给我们完整的错误吗?
  • 顺便说一句,您的函数应该返回 final_xyz_list 而不是试图使其成为全局变量。
  • step=+1 --&gt; step+=1

标签: python list while-loop append


【解决方案1】:

无需将这三个项目附加到 2 个不同的 while 循环中。如果您使用 for 循环,它也会更简单。在这种情况下:

for step in range(0, 50):
    final_xyz_list.append(carbon_final_list[step]) 
    final_xyz_list.append(oxygen_final_list[step]) 
    final_xyz_list.append(hydrogen_final_list[step]) 

编辑:另外,我刚刚注意到错误,您使用step =+ 1,这与说step = +1step = 1 相同。这就是为什么你得到一个内存错误,你一直将 step 定义为 1,它在 0 到 50 之间,所以 while 循环继续进行。你可能想写的是step += 1,它以 1 递增,而不是设置为 1

【讨论】:

  • 是否会使用 for 循环而不是 while 循环来解决 MemoryError 问题?
  • 我不知道,我会试试看。也许你没有足够的内存来运行这个程序(我怀疑,因为它的要求不高)
猜你喜欢
  • 2019-09-14
  • 2012-06-19
  • 2021-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 1970-01-01
  • 2016-07-23
相关资源
最近更新 更多