Winterflags Winterflags - 4 months ago 6
Python Question

"TypeError: Bool is not iterable" in any() iteration with boolean criteria

In Python 2.7, I want to check the similarity between one string, and strings in a list, until it finds a match.

from difflib import SequenceMatcher

def similar(a, b):
return SequenceMatcher(None, a, b).ratio()

correctList = ["thanks", "believe", "definitely"]

myString = "thansk"

for correctWord in correctList:
ratio = similar(correctWord, myString)
if ratio > 0.9:
myString = correctWord

print myString
>>> "thanks"

I would like to simplify the
iteration into fewer lines, to something like:

if similar(myString, any([correctWord for correctWord in correctList])) > 0.9:
myString = correctWord

I'm not entirely sure about the correct logic here, but in either case variants of this syntax throws the error:

TypeError: ("'bool' object is not iterable", u'occurred at index 0')

What would be the proper way to achieve this?


You are stopping as soon as you find the first string with similarity > 0.9, starting with "thansk" as a candidate. So I think this is equivalent:

myString = "thansk"

myString = next((w for w in correctList if similar(w, myString) > 0.9), myString)