Python代码第一次可以正常运行,但是第二次失败 [英] Python code works fine first time, but fails second time

查看:1153
本文介绍了Python代码第一次可以正常运行,但是第二次失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次从Notebook运行此代码块时,效果很好:

The first time I run this block of code from Notebook it works fine:

#Which letters and how many
letters = ["a","b","c"]
noOfLetters = len(letters)

#Looking for all permutations
resultA = []
from itertools import permutations
for i in range(noOfLetters):
    resultA.append(list(permutations(letters,i+1)))

如果再次运行它(不重新启动内核),则会出现以下错误:

If I run it again (without restarting the Kernel) I get the following error:

TypeError                                 Traceback (most recent call last)
<ipython-input-5-4050a4ce7a36> in <module>()
      7 from itertools import permutations
      8 for i in range(noOfLetters):
----> 9     resultA.append(list(permutations(letters,i+1)))

TypeError: 'list' object is not callable

推荐答案

假设笔记本"是Jupyter(以前是ipython笔记本),则必须注意jupyter保留所有变量的状态.

Assuming "notebook" is Jupyter (previously ipython notebooks), you must be careful that jupyter keeps the state of all variables.

->表示第二次运行从已经初始化为第一次运行结束时具有的值的变量开始.

--> that means that the second run starts with variables already initialized at the value they had at the end of the first run.

避免这种情况的一种方法是重新启动内核.另一个是删除所有变量;另一个是每次运行时都要初始化所有变量.

One way to avoid that is to restart the kernel; another is to delete all variables; one more is to initialize all your variables each time you run.

来自文档:

要重新启动内核(即计算引擎),请单击菜单内核->重新启动.这对于从头开始计算非常有用(例如,删除变量,关闭打开的文件等).

To restart the kernel (i.e. the computational engine), click on the menu Kernel -> Restart. This can be useful to start over a computation from scratch (e.g. variables are deleted, open files are closed, etc...).

这篇关于Python代码第一次可以正常运行,但是第二次失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆