Python代码在Jupyter中显示错误

时间:2016-01-06 09:07:36

标签: python anaconda jupyter jupyter-notebook

以下是在命令行中显示正确输出但在Jupyter中显示错误的python代码。我安装了名为Anaconda 2.4.1(64位)的python发行版,其中包含Python 2.7.11。

以下代码采用嵌套列表并打印展平列表。

def printWholeList(list1):

    for iterator in list1 :
        if(isinstance(iterator,list)):
                printWholeList(iterator)
        else:
            print(iterator)

list1 = ['a' ,'b' ,['c','d',['p','h']]]
printWholeList(list1)

在命令行输出:

  

C:\用户\ KarmicSmoke>蟒   C:\ Users \ KarmicSmoke \ Downloads \ FirstProg.py
a
b
c
  d
p h h

Jupyter的输出:

-

--------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-64-3df571b6bccc> in <module>()
      8 
      9 list1 = ['a' ,'b' ,['c','d',['p','h']]]
---> 10 printWholeList(list1)
     11 
     12 

<ipython-input-64-3df571b6bccc> in printWholeList(list1)
      2 
      3     for iterator in list1 :
----> 4         if(isinstance(iterator,list)):
      5                 printWholeList(iterator)
      6         else:

TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

为什么会出现此错误?

更新:
之前我将'list'声明为局部变量名,并且出现了错误。然后,我将其更改为'list1',如上所示。这就是我在Jupyter笔记本中所做的一切。现在我关闭它,再次打开它,VOILA显示正确的输出。我应该从Jupyter的这种行为中推断出什么? -

1 个答案:

答案 0 :(得分:1)

尝试:

def printWholeList(list1):

    for it in list1 :
        if(isinstance(it,__builtins__.list)):
                printWholeList(it)
        else:
            print(it)

list1 = ['a' ,'b' ,['c','d',['p','h']]]
printWholeList(list1)

您可能已在笔记本中定义了一个var命名列表。 不要使用保留关键字!