How can I return in python a word which has the same length as a word searched. For example, I am looking for a closest match for the word "three" in a list of ["three","tea","tree"] and I want to return the first occurence of the same length word.
I need to do it using generator or some list comprehensions as I have a really big set of data. Until now I have this function:
matches_list= dl.get_close_matches(word.lower(),list_of_words)
if matches_list:
new_word= (w for w in matches_list if (len(word)==len(w)))
print new_word.next()
Which prints just fine until the 4th or 5th iteration where I get this message error:
print new_word.next()
StopIteration
Use the next()
function and supply a default:
new_word = (w for w in matches_list if len(word) == len(w))
print next(new_word, 'nothing found')
The StopIteration
exception is raised because your generator reached the end without a (further) match. If you give a second argument to the next()
function, then it'll catch that exception and return that second argument as a default instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.