简体   繁体   English

无法识别 Python 中循环内的变量

[英]Not recognized variable inside a loop in Python

I am trying to run loop in Python while specifying the variable x and y inside the loop.我试图在 Python 中运行循环,同时在循环内指定变量xy When I run the following loop:当我运行以下循环时:

   my_funcs = {}
    for i in range(len(data) - 1):
        def foo(x, y):
            x = data[i]['body']
            y = data[i+1]['body']
            tfidf = vectorizer.fit_transform([x, y])
            return ((tfidf * tfidf.T).A)[0,1]


        foo.func_name = "cosine_sim%d" % i
        my_funcs["cosine_sim%d" % i] = foo
        print(foo(x,y))

I get the strange error: x is not defined in the line print(foo(x,y)) Any idea why on earth this might be happening since I have stated that x = data[i]['body'] ?我收到一个奇怪的错误: x is not defined在行中x is not defined print(foo(x,y))知道为什么会发生这种情况,因为我已经声明x = data[i]['body']

Thanks in advance提前致谢

If everything else is correct, I think you should move that method outside of the loop.如果其他一切都正确,我认为您应该将该方法移到循环之外。

You only defined x within foo , so the print line doesn't know about it.您只在foo定义了x ,因此print行不知道它。 Plus, you were overwriting the x parameter of foo anyways另外,您无论如何都覆盖了foox参数

def foo(x, y):
    tfidf = vectorizer.fit_transform([x, y])
    return ((tfidf * tfidf.T).A)[0,1]

my_funcs = {}
for i in range(len(data) - 1):
    x = data[i]['body']
    y = data[i+1]['body']
    foo.func_name = "cosine_sim%d" % i
    my_funcs["cosine_sim%d" % i] = foo
    print(foo(x,y))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM