LoginSignup
1
1

More than 1 year has passed since last update.

heapq.nlargest(n, iterable)でリストの上位n番目までをスッキリ抽出

Posted at

はじめに

heapq.nlargest(n, iterable, key=None)
はリストなどの上位n番目までの要素をリストで返します。。調べても記事がなかったので書いておきます。

説明

heapq.nlargest(n, iterable, key=None)
ではiterableで定義されるデータセットのうち、最大値から降順にn個の値のリストを返します。

つまり、
sorted(iterable,key=None,reverse=True)[:n]
と同義です。

実行

sample=[5,7,3,12,7,3,1]
を例に取って実行します。

コード

sample=[5,7,3,12,7,3,1]

print(heapq.nlargest(5,sample))
print(sorted(sample,reverse=True)[:5])

結果

[12, 7, 7, 5, 3]
[12, 7, 7, 5, 3]

次に、
sample=[("c",5),("b",7),("e",3),("f",12),("a",7),("d",3),("g",1)]
を例にとって実行します。

コード

sample=[("c",5),("b",7),("e",3),("f",12),("a",7),("d",3),("g",1)]

# 普通にソート
print(heapq.nlargest(5,sample))
print(sorted(sample,reverse=True)[:5])

# 第二引数に関してソート
print(heapq.nlargest(5,sample,key=lambda t:t[1]))
print(sorted(sample,reverse=True,key=lambda t:t[1])[:5])

結果

[('g', 1), ('f', 12), ('e', 3), ('d', 3), ('c', 5)]
[('g', 1), ('f', 12), ('e', 3), ('d', 3), ('c', 5)]

[('f', 12), ('b', 7), ('a', 7), ('c', 5), ('e', 3)]
[('f', 12), ('b', 7), ('a', 7), ('c', 5), ('e', 3)]

まとめ

sortedを使うより多少コード量が減るし、見栄え的にもわかりやすいので、heapqをインポートしているような場面では積極的に使っていこうと思っています。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1