Home > Mobile >  How I can convert for loop in python using map function
How I can convert for loop in python using map function

Time:01-04

this is the code that I want to convert it using map function in python

for joint_word in joint_words:
    if joint_word in wordset:
        # word in joint_words found in sentence, just populate the index
        wovec[i] = windex[joint_word]
    else:
        sim_word, max_sim = most_similar_word(joint_word, wordset)
        if max_sim > ETA:
            wovec[i] = windex[sim_word]
        else:
            wovec[i] = 0
    i = i   1

CodePudding user response:

Well, the raw translation would be:

def lookup(word):
    if word in wordset:
        return windex[word]
    sim_word, max_sim = most_similar_word(word, wordset)
    return windex[sim_word] if max_sim > ETA else 0

wovec = list(map(lookup, joint_words))

If wovec will be used as an iterable, then you don't need the cast to list.

CodePudding user response:

In Python 3.8 , you can take the simple function Tim Roberts made, and turn it into a one-line abomination:

wovec = list(map(lambda word: windex[word] if word in wordset else (windex[msw[0]] if ((msw := most_similar_word(word, wordset))[1]) > ETA else 0), joint_words))

Basically, don't unpack the result of most_similar_word(word, wordset), instead assign it within the expression and access by index. Enjoy!

In case it wasn't clear, I'm endorsing Tim's answer. Please don't ever use something like what I wrote. Not to mention that comprehensions generally tend to be marginally faster than maps.

  • Related