newtoCS
newtoCS

Reputation: 113

Update the previous element of list in a loop based on a condition

I am trying clean the names of the list.

results = []
mylist = ['jellyfish','jellyish','jellyish','smellyfish']

#convert to unicode
mylist = [unicode(i) for i in mylist]

for i, j in enumerate(mylist):
    current = mylist[i] 
    previous = mylist[i-1]
    current_score = jf.jaro_winkler(current, previous)
    if(current_score > 0.96):
        current=previous
    print current, current_score

I get the following results:

The first two records is what i want, but I need jellyish to be changed to jellyfish as well.

Expected results should be..

Upvotes: 0

Views: 69

Answers (2)

Ameya Pandilwar
Ameya Pandilwar

Reputation: 2778

The values in the original list are not being updated. You need to do it by adding the following line -

previous = mylist[i-1]
current_score = jf.jaro_winkler(current, previous)
if (current_score > 0.96):
    mylist[i] = mylist[i-1]
    current = previous

Upvotes: 0

cs95
cs95

Reputation: 402333

Let's focus on what needs to be changed - you're currently doing current = previous which does nothing but reassign the variable current to another object.

What you need to do is actually update the list in place. You're already iterating over the indices, so you'll just need to make a small change.

mylist = ['jellyfish', 'jellyish', 'jellyish', 'smellyfish']

for i, v in enumerate(mylist[1:], 1):
    p, c = mylist[i - 1], v
    if jf.jaro_winkler(p, c) > .96:
        mylist[i] = p

Upvotes: 1

Related Questions