[英]Python lambda function in sorted()
This woking code gives me the 5 most relevant documents for a topic out of my corpus. 此启动代码为我提供了与主题相关的5个最相关的文档。
most_relevant_docs = sorted(bow_corpus, reverse=True, key=lambda doc: abs(dict(doc).get(topic_number, 0.0)))
print most_relevant_docs[ :5]
But since the corpus is not readable by human I want to zip an index to the corpus so I can recover the depending documents. 但是由于该语料库无法被人类读取,因此我想将索引压缩到该语料库中,以便可以恢复相关文档。
corpus_ids = range(0,len(corpus))
most_relevant_docs = sorted(zip(corpus_ids, bow_corpus), reverse=True, key=lambda my_id, doc : abs(dict(doc).get(topic_number, 0.0)))
print most_relevant_docs[ :5]
Where do I have to adapt the lambda function so it returns the id together with the document? 我必须在哪里适应lambda函数,以便它返回ID和文档?
Try this 尝试这个
sortingFunc = lambda doc: abs(dict(doc).get(topic_number, 0.0))
corpus_ids = range(0,len(corpus))
most_relevant_docs = sorted(zip(corpus_ids, bow_corpus), reverse=True, key=lambda pair: sortingFunc(pair[1]))
When you zip it, each element becomes like (index, value)
, so the original sorting key wouldn't work. 压缩它时,每个元素都变得像
(index, value)
,所以原始的排序键将不起作用。 You'd need to modify it so it sorts by the value as opposed to the pair 您需要对其进行修改,以便按值(而不是对)进行排序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.