2015-05-11 6 views
6

Jeśli mam dict list, takich jak:Jak liczyć wielkość list z dyktowaniem?

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

i chcę zgadzają wielkości list, czyli liczbę identyfikatorów> 0,> 1,> 2 ... etc

.

Czy istnieje prostszy sposób niż zagnieżdżone pętle tak:

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 

Odpowiedz

2

bym użyć collections.Counter() object zebrać długości, a następnie gromadzić kwot:

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 

Tak więc ta liczba zbiera się dla każdej długości, a następnie tworzy słownik z łącznymi długościami. To jest algorytm O (N); Chcesz pętla nad wszystkimi wartościami raz, a następnie dodać na niektórych mniejszych pętli prostej (dla max() i pętli akumulacyjne):

>>> 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

Tak, jest lepszy sposób.

pierwsze, indeks identyfikatory długością ich danych:

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) 

Teraz utworzyć 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 

Ma O (n) złożoność zamiast O (n²) więc jest również znacznie szybszy w przypadku dużych zbiorów danych.