Python 在模块内部使用时未定义 itertools

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41252311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:40:38  来源:igfitidea点击:

itertools not defined when used inside module

pythonfunctionmoduleanacondaitertools

提问by Adam

I save my custom functions in a separate module that I can call when I need to. One of my new functions uses itertools, but I keep getting a name error.

我将自定义函数保存在一个单独的模块中,我可以在需要时调用该模块。我的一个新函数使用 itertools,但我不断收到名称错误。

NameError: name 'itertools' is not defined

It's really weird. I can import itertools in the console just fine, but when I call my function, I get a name error. Usually I can use functions from other libraries (pandas, sklearn, etc.) inside a custom function just fine as long as I import the library first.

这真的很奇怪。我可以在控制台中导入 itertools 就好了,但是当我调用我的函数时,出现名称错误。通常我可以在自定义函数中使用来自其他库(pandas、sklearn 等)的函数,只要我先导入库就行了。

BUT if I import itertools in the console, copy and paste my function into the console, and then call the function, it works fine.

但是,如果我在控制台中导入 itertools,将我的函数复制并粘贴到控制台中,然后调用该函数,它就可以正常工作。

It's making me crazy, but I'm thinking maybe I'm just not understanding the rules of modules or something.

这让我发疯了,但我想也许我只是不理解模块的规则或其他东西。

here's the function i'm using in the module. it's simply copy and pasted from one of the sklearn examples:

这是我在模块中使用的功能。它只是从 sklearn 示例之一复制和粘贴:

import itertools    
def plot_confusion_matrix(cm, classes,
                              normalize=False,
                              title='Confusion matrix',
                              cmap=plt.cm.Blues):
        import itertools
        plt.imshow(cm, interpolation='nearest', cmap=cmap)
        plt.title(title)
        plt.colorbar()
        tick_marks = np.arange(len(classes))
        plt.xticks(tick_marks, classes, rotation=45)
        plt.yticks(tick_marks, classes)

        if normalize:
            cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
            print("Normalized confusion matrix")
        else:
            print('Confusion matrix, without normalization')

        print(cm)

        thresh = cm.max() / 2.
        for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
            plt.text(j, i, cm[i, j],
                     horizontalalignment="center",
                     color="white" if cm[i, j] > thresh else "black")

        plt.tight_layout()
        plt.ylabel('True label')
        plt.xlabel('Predicted label')

I tried importing it inside the function, inside the module, and inside the file where I am calling it - all with no luck. If I import it in the console its fine. Even after it's been imported in the console, if I run it inside the file I'm working on again, it gives the same error.

我尝试将它导入到函数内部、模块内部以及我调用它的文件中——但都没有成功。如果我在控制台中导入它就好了。即使在控制台中导入它之后,如果我再次在我正在处理的文件中运行它,它也会出现相同的错误。

回答by Adam

It works now.

它现在有效。

IMPORTANT LESSON: If you edit a module, you must close and reopen spyder/ipython/whatever. Simply resetting the kernel is not sufficient. Stupid of me, I know, but maybe maybe this answer will save someone time.

重要教训:如果你编辑一个模块,你必须关闭并重新打开 spyder/ipython/whatever。简单地重置内核是不够的。我知道我很愚蠢,但也许这个答案会节省一些时间。

回答by Vong Ho

You just change
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):

你只要改变
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):

To:

到:

for i in range (cm.shape[0]): for j in range (cm.shape[1]):

for i in range (cm.shape[0]): for j in range (cm.shape[1]):

回答by Qin Peng Michelle

You can first use from itertools import product, then change itertools.product into simply product. That should work.

您可以首先使用from itertools import product,然后将 itertools.product 更改为简单的product。那应该工作。