简体   繁体   中英

Python lambda function in sorted()

This woking code gives me the 5 most relevant documents for a topic out of my corpus.

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?

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. You'd need to modify it so it sorts by the value as opposed to the pair

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM