Come posso recuperare l'elenco dei primi 3 da un dizionario?valori massimi dal dizionario
>>> d
{'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4}
Risultato atteso:
and: 23
only: 21
this: 14
Come posso recuperare l'elenco dei primi 3 da un dizionario?valori massimi dal dizionario
>>> d
{'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4}
Risultato atteso:
and: 23
only: 21
this: 14
Uso collections.Counter
:
>>> d = Counter({'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4})
>>> d.most_common()
[('and', 23), ('only.', 21), ('this', 14), ('test', 4), ('a', 2), ('is', 2), ('work', 2), ('will', 2), ('as', 2)]
>>> for k, v in d.most_common(3):
... print '%s: %i' % (k, v)
...
and: 23
only.: 21
this: 14
oggetti contatore offrono vari altri vantaggi, come ad esempio rendendo quasi banale per raccogliere i conteggi in primo luogo.
>>> d = {'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4}
>>> t = sorted(d.iteritems(), key=lambda x:-x[1])[:3]
>>> for x in t:
... print "{0}: {1}".format(*x)
...
and: 23
only.: 21
this: 14
Le risposte che hai già sono corrette, vorrei comunque creare la mia funzione chiave da utilizzare quando chiamata ordinata().
d = {'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4}
# create a function which returns the value of a dictionary
def keyfunction(k):
return d[k]
# sort by dictionary by the values and print top 3 {key, value} pairs
for key in sorted(d, key=keyfunction, reverse=True)[:3]:
print "%s: %i" % (key, d[key])
Considerate le soluzioni di cui sopra:
def most_popular(L):
# using lambda
start = datetime.datetime.now()
res=dict(sorted([(k,v) for k, v in L.items()], key=lambda x: x[1])[-2:])
delta=datetime.datetime.now()-start
print "Microtime (lambda:%d):" % len(L), str(delta.microseconds)
# using collections
start=datetime.datetime.now()
res=dict(collections.Counter(L).most_common()[:2])
delta=datetime.datetime.now()-start
print "Microtime (collections:%d):" % len(L), str(delta.microseconds)
# list of 10
most_popular({el:0 for el in list(range(10))})
# list of 100
most_popular({el:0 for el in list(range(100))})
# list of 1000
most_popular({el:0 for el in list(range(1000))})
# list of 10000
most_popular({el:0 for el in list(range(10000))})
# list of 100000
most_popular({el:0 for el in list(range(100000))})
# list of 1000000
most_popular({el:0 for el in list(range(1000000))})
lavoro sul set di dati dict di dimensioni da 10^1 a 10^6 dict di oggetti come
print {el:0 for el in list(range(10))}
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}
Abbiamo i seguenti parametri di riferimento
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
Microtime (lambda:10): 24
Microtime (collections:10): 106
Microtime (lambda:100): 49
Microtime (collections:100): 50
Microtime (lambda:1000): 397
Microtime (collections:1000): 178
Microtime (lambda:10000): 4347
Microtime (collections:10000): 2782
Microtime (lambda:100000): 55738
Microtime (collections:100000): 26546
Microtime (lambda:1000000): 798612
Microtime (collections:1000000): 361970
=> None
Così possiamo diciamo che per le piccole liste si usa lambda
, ma per la lista enorme, collections
ha prestazioni migliori.
Vedere il valore di riferimento here.
D'accordo che Counter è il modo migliore per andare se si desidera contare anche le cose. Ma se vuoi solo i primi 3 valori in un dettato già creato, sembra un eccesso. :) –
Dipende dalla dimensione del dizionario. L'ordinamento del dizionario è O (n log n), la creazione di un contatore e l'estrazione di 'k' il più grande è solo O (n log k). Per grandi 'n' e piccoli' k' rendono l'opzione Contatore molto più efficiente. – Duncan
In realtà, per soli 3 valori principali, userei la funzione 'heapq.nlargest()'; è più efficiente di ordinare l'intera sequenza. Questo è ciò che 'Counter()' usa internamente. –