TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

K-way merge - Python way

25 pointsby mmihaljevicover 12 years ago

2 comments

cypherpunks01over 12 years ago
Re-sorting with sorted() in #2 defeats the purpose of the k-way merge, you may as well just materialize all the lists and sort them.<p>I didn't know about heapq.merge before, that seems like an efficient way to go. Usually when I do k-way merges it's over a data stream, so I almost always want an iterator.
评论 #4974853 未加载
评论 #4974729 未加载
andrewcookeover 12 years ago
<p><pre><code> &#62;&#62;&#62; from heapq import merge &#62;&#62;&#62; def kmerge(*lists): ... return merge(*map(sorted, lists)) ... &#62;&#62;&#62; list(kmerge([1,2,3],[6,5,4],[2,2])) [1, 2, 2, 2, 3, 4, 5, 6]</code></pre>