CKTIS / Python
heapq.nsmallest
Restituisce fino a n elementi originali per chiave crescente, per esempio le offerte più economiche.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
heapq.nsmallest(n, iterable, key=None)Restituisce fino a n elementi originali per chiave crescente, per esempio le offerte più economiche.
Senza key vengono confrontati gli elementi stessi. Le chiavi uguali mantengono l’ordine di ingresso. Nell’esempio entrambi i 2 precedono 5.
Un ingresso contenente solo 7 dà un unico risultato e un ingresso vuoto dà una lista vuota.
from heapq import nsmallest
rows = [("A", 4), ("B", 1), ("C", 1), ("D", 2)]
assert nsmallest(2, rows, key=lambda r: r[1]) == [("B", 1), ("C", 1)]
assert nsmallest(0, rows) == [] and nsmallest(3, []) == []
Esempi
import heapq
print(heapq.nsmallest(3, [5, 2, 2, 8]))
print(heapq.nsmallest(5, [7]))
Risultato
[2, 2, 5] [7]
Un ingresso contenente solo 7 dà un unico risultato e un ingresso vuoto dà una lista vuota.