nested loop over list and dynamically create variables

Viewed 100

I have a list of sentences and I want to perform some action on two sentences each time, but not for al of the sentences.

for example:

list= ["aaaaa","bbbbb","ccccc","ddddd","eeeee"]
similarity_a-d = sim("aaaaa","ddddd")
similarity_a-e = sim("aaaaa","eeeee")
similarity_b-d = sim("bbbbb","ddddd")
similarity_b-e = sim("bbbbb","eeeee")
similarity_c-d = sim("ccccc","ddddd")
similarity_c-e = sim("ccccc","eeeee")

That's what I tried:

similarity={}
for i,vec_lda_topic in enumerate(vec_lda_topics)[:numOfUSs]:
    for j,vec_lda_topic in enumerate(vec_lda_topics)[numOfUSs:]:
        similarity["sim{0}-{1}".format(i,j)] = gensim.matutils.cossim(vec_lda_topics[i], vec_lda_topics[j])
        print('similarity between docs ', i, ' and ',j,': ', similarity["sim{0}-{1}".format(i,j)])

and receive the following error:

TypeError: 'enumerate' object is not subscriptable

And besides the error, maybe there is a better way to do this?

2 Answers

enumerate the sliced list, don't slice the enumerated list (do this in both places)

for i,vec_lda_topic in enumerate(vec_lda_topics[:numOfUSs]):

Your issue is that you're subscripting in the wrong place:

similarity={}
for i, vec_lda_topic in enumerate(vec_lda_topics[:numOfUSs]):
    for j, vec_lda_topic in enumerate(vec_lda_topics[numOfUSs:]):
        simmilarity["sim{0}-{1}".format(i,j)] = gensim.matutils.cossim(vec_lda_topics[i], vec_lda_topics[j])
        print('similarity between docs ', i, ' and ', j, ': ', simmilarity["sim{0}-{1}".format(i,j)])

All I did was move the subscript inside the call to enumerate.

Related