2015-05-11 8 views
6

Se ho un dict di liste come:Come contare le dimensioni delle liste con un dict?

{ 
    'id1': ['a', 'b', 'c'], 
    'id2': ['a', 'b'], 
    # etc. 
} 

e voglio coincidere le dimensioni delle liste, vale a dire il numero di ID> 0,> 1,> 2 ... ecc

.

c'è un modo più facile di cicli for innestati in questo modo:

dictOfOutputs = {} 
for x in range(1,11): 
    count = 0 
    for agentId in userIdDict: 
     if len(userIdDict[agentId]) > x: 
      count += 1 
    dictOfOutputs[x] = count   
return dictOfOutputs 

risposta

2

userei un collections.Counter() object per raccogliere lunghezze, poi si accumulano le somme:

from collections import Counter 

lengths = Counter(len(v) for v in userIdDict.values()) 
total = 0 
accumulated = {} 
for length in range(max(lengths), -1, -1): 
    count = lengths.get(length, 0) 
    total += count 
    accumulated[length] = total 

Quindi questo raccoglie i conteggi per ogni lunghezza, quindi crea un dizionario con lunghezze cumulative. Questo è un algoritmo O (N); si esegue un ciclo su tutti i valori di una volta, quindi aggiungere su alcuni cicli più piccoli dritto (per max() e il ciclo di accumulazione):

>>> from collections import Counter 
>>> import random 
>>> testdata = {''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(5)): [None] * random.randint(1, 10) for _ in range(100)} 
>>> lengths = Counter(len(v) for v in testdata.values()) 
>>> lengths 
Counter({8: 14, 7: 13, 2: 11, 3: 10, 4: 9, 5: 9, 9: 9, 10: 9, 1: 8, 6: 8}) 
>>> total = 0 
>>> accumulated = {} 
>>> for length in range(max(lengths), -1, -1): 
...  count = lengths.get(length, 0) 
...  total += count 
...  accumulated[length] = total 
... 
>>> accumulated 
{0: 100, 1: 100, 2: 92, 3: 81, 4: 71, 5: 62, 6: 53, 7: 45, 8: 32, 9: 18, 10: 9} 
0

Sì, c'è un modo migliore.

In primo luogo, indice gli ID per la lunghezza dei loro dati:

my_dict = { 
    'id1': ['a', 'b', 'c'], 
    'id2': ['a', 'b'], 
} 

from collections import defaultdict 
ids_by_data_len = defaultdict(list) 

for id, data in my_dict.items(): 
    my_dict[len(data)].append(id) 

Ora, creare il dict:

output_dict = {} 
accumulator = 0 
# note: the end of a range is non-inclusive! 
for data_len in reversed(range(1, max(ids_by_data_len.keys()) + 1): 
    accumulator += len(ids_by_data_len.get(data_len, [])) 
    output_dict[data_len-1] = accumulator 

Questo ha O (n) la complessità piuttosto che O (n²), quindi è anche molto più veloce per grandi serie di dati.

Problemi correlati