python - Finding values in a dictionary if key matches in a range -


i have list , dictionary:

l = [1, 4, 22, 33] dict = {1: 'red', 17: 'green', 33: 'blue'}; 

my goal return new list composed values (colors) associated each element in l if between key key+16.

i know how retrieve value if element of list matches key in dictionary, don't know how consider each key range , assign color every element in l.

the expected output be:

['red', 'red', 'green', 'blue'] 

i know generating list dict able iterate on 2 lists, finding values in range. problem working 2 of more 80,000 elements per list, time , thought dictionary better.

you can integer division:

>>> l = [1, 4, 22, 33] >>> dct = {1: 'red', 17: 'green', 33: 'blue'}  # don't name own dictionary dict >>> [dct[16*((x-1)//16)+1] x in l] ['red', 'red', 'green', 'blue'] 

basically, maps every number e.g. 1 16 inclusive 1, every number 17 32 inclusive 17, etc.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -