-2

How can I convert the following code into a list comprehension?

for i in range(xy-1):
    for b in range(i+1, xy):
        if(fuzz.token_set_ratio(Names[i], Names[b]) >= 90):
            FuzzNames[b].append(ID[i])
        else:
            pass

Thanks for helping.

6
  • 6
    I always refer to this answer when converting back and forth. Commented Aug 9, 2022 at 20:39
  • This is made a little more tricky because it doesn't return a single list. It's filling in some values, and leaving other values alone. Commented Aug 9, 2022 at 20:43
  • I don't think this can be a list comprehension. It's not creating new lists, it's appending to existing lists. And it's appending to a different list each time through the loop. I thought it could be done by swapping the order of the for loops, but b is dependent on i. Commented Aug 9, 2022 at 20:46
  • I am doing a fuzzy search between 32,000 lines of data, the code took 7 hours but did not finish. I read about how to make my code faster, one of the solutions was list comprehension. This is the main block in my code, so I wondered how to do it Commented Aug 9, 2022 at 20:53
  • The list processing is NOT your bottleneck. Have you timed the individual fuzzy searches? If a single search takes 1 second, then 32,000 searches will take 9 hours. Commented Aug 9, 2022 at 20:59

1 Answer 1

1

You could do something like this:

indices = [(i,b) for i in range(xy-1) for b in range(i+1, xy) if fuzz.token_set_ratio(Names[i], Names[b]) >= 90]

for i, b in indices:
  FuzzNames[b].append(ID[i])

However, the way you originally wrote it is more readable and easier to understand, and it's not likely that you need that list of indices later on.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a little faster. The data I am working with have 11 columns, every one with ten of thousands of line. This will save hours for me, thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.