1

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
2
  • This would not be an appropriate use of map(). map() creates a list of the results of a function, but you're not creating a list here. Commented Jan 3, 2022 at 6:03
  • Well, assuming i started out as 0, yes, they really are. Commented Jan 3, 2022 at 6:05

2 Answers 2

2

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.

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

3 Comments

Without the call to list, it will only be usable once
Right, hence my warning about using it as an iterable.
I did warn OP to select your answer. Twice.
0

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.

1 Comment

Thank you Both , I select Time's answer

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.