简体   繁体   中英

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. 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'] ?

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. Plus, you were overwriting the x parameter of foo anyways

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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