Convert list to another form but providing same information

Steven D'Aprano steve at pearwood.info
Tue Mar 22 06:49:00 EDT 2016


On Tue, 22 Mar 2016 12:35 pm, Paul Rubin wrote:

> Maurice <mauricioliveiraguarda at gmail.com> writes:
>> I have a list such [6,19,19,21,21,21]
>> Therefore the resulting list should be:
>> [0,0,0,0,0,0,1,0,0,0...,2,0,3,0...0]
> 
> Rather than a sparse list you'd typically want a dictionary (untested):
> 
>   from collections import defaultdict
>   the_list = [0,0,0,0,0,0,1,0,0,0...,2,0,3,0...0]
>   ...
>   days = defaultdict(int)
>   for t in the_list:
>      days[t] += 1
> 
> this results in days being the defaultdict { 6:1, 19:2, 21:3 }.

For just 3 items out of 32, doing this as an optimisation is barely worth
it. Using Python 3.4, I get 168 bytes for the list solution and 152 bytes
for a default dict solution:

py> print(days)
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0]
py> sys.getsizeof(days)
168

py> from collections import defaultdict
py> d = defaultdict(int)
py> d.update({ 6:1, 19:2, 21:3 })
py> sys.getsizeof(d)
152

By all means use whichever solution suits you best, but don't expect to save
much memory in a "spare array" of only 32 items :-)



-- 
Steven




More information about the Python-list mailing list