raph
raph

Reputation: 119

How can I stop the repetition of the same element in a loop

I have a problem in python with my loop for.

I have a repetition of the same element and I don't know why.

Here it's my code :

x=0
liste=[]
for x in range(len(valeur)):
    for i in range(x+1,len(valeur)):
        ed = nltk.edit_distance(valeur[x],valeur[i])
        dico={"titre":valeur[x],"titre_compare":valeur[i], "distance":ed}
        a=((dico["titre"],(dico["titre_compare"]),(dico["distance"])))

        for z in range (len(a)):
            if a[2]<6 and a[0] != ' None ' and a[1] != ' None ' and a[2] != ' None ' :

                print(a)

My code works perfectly but I don't understand why I got this :

(' K. Hardono ', ' Cardon. ', 5)
(' K. Hardono ', ' Cardon. ', 5)
(' K. Hardono ', ' Cardon. ', 5)

and not only this :

(' K. Hardono ', ' Cardon. ', 5)

I tried to search and I discovered it :

When I put this for example :

a=((dico["titre"],"&&",(dico["titre_compare"]),"&&",(dico["distance"])))

It returns 5 times

(' K. Hardono ', ' Cardon. ', 5)
(' K. Hardono ', ' Cardon. ', 5)
(' K. Hardono ', ' Cardon. ', 5)
(' K. Hardono ', ' Cardon. ', 5)
(' K. Hardono ', ' Cardon. ', 5)

So I know that my repetition of the same element provide of my number element of my dictionary in python but I don't know how I can have only 1 element and not a repetition.

Thanks if you can help me

Upvotes: 0

Views: 40

Answers (1)

AirSquid
AirSquid

Reputation: 11903

Well, it looks like the tuple a that you are making has a length of 3, right?

So when you make your next for loop with z, z will take on the values of [0, 1, 2] during the loop. That loop does the same thing each time (no dependency on z) so it will print a 3 times.

Look again at your loop with z and think about what you are trying to do. Also where you define your tuple a the parenthesis are a bit out of whack...

Upvotes: 1

Related Questions