Why my for-loop has only one result after a python list iterator?

Viewed 45

The following codes with for-loop only return one-item while I expected it could return many-item. For example, It returned actually:

0.3273

What I expected is

0.8372
0.2847
0.1837
0.3273
...

Should I use .append() or something else? Please give me some detailed code advice. Thank you.

def phrase_similarity(phrase):
    phrase_vec = phrase_model[phrase]
    for a_word in phrase_model.keys():
        a_val = phrase_model[a_word]
        cos_dis = cosine_similarity(phrase_vec, a_val) #it's numpy.ndarray
        cos_dis_str = str(cos_dis.tolist()).strip('[[]]')

    return cos_dis_str
3 Answers

Let cos_dis_str be an empty list

cos_dis_str=[]

Then a simple append would fix that

cos_dis_str.append(str(cos_dis.tolist()).strip('[[]]'))

When the For loop is executing, each time the os_dis_str is getting overwritten. So make sure that you create a list for that and keep on appending onto that. Then return the list. You can access each of the individual values from there.

cos_dis_str.append(str(cos_dis.tolist()).strip('[[]]'))

Also initialize cos_dis_str = [], outside the For loop but within the function. Hope this helps to get an understanding.

you can change your code this way.

def phrase_similarity(phrase):

    phrase_vec = phrase_model[phrase]
    cos_dis_str = []

    for a_word, a_val in phrase_model.items():
        cos_dis = cosine_similarity(phrase_vec, a_val).tolist()).strip('[[]]') #it's numpy.ndarray
        cos_dis_str.append(str(cos_dis))

    return '\n'.join(cos_dis_str)
Related