[英]How I can convert for loop in python using map function
这是我想在 python 中使用 map function 转换它的代码
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
好吧,原始翻译是:
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))
如果wovec
将用作可迭代对象,则不需要强制转换为list
。
在 Python 3.8+ 中,您可以使用Tim Roberts制作的简单 function 并将其变成单行可憎:
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))
基本上,不要解压缩most_similar_word(word, wordset)
的结果,而是在表达式中分配它并按索引访问。 享受!
如果不清楚,我支持蒂姆的回答。 请永远不要使用我写的东西。 更不用说理解通常比地图快一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.