Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice list to ordered chunks

Tags:

python

list

slice

I have dictionary like:

item_count_per_section = {1: 3, 2: 5, 3: 2, 4: 2}

And total count of items retrieved from this dictionary:

total_items = range(sum(item_count_per_section.values()))

Now I want to transform total_items by values of dictionary following way:

items_no_per_section = {1: [0,1,2], 2: [3,4,5,6,7], 3:[8,9], 4:[10,11] }

I.e. slice total_items sequencially to sublists which startrs from previous "iteration" index and finished with value from initial dictionary.

like image 218
Alex G.P. Avatar asked May 26 '26 17:05

Alex G.P.


1 Answers

You don't need to find total_items at all. You can straightaway use itertools.count, itertools.islice and dictionary comprehension, like this

from itertools import count, islice
item_count_per_section, counter = {1: 3, 2: 5, 3: 2, 4: 2}, count()
print {k:list(islice(counter, v)) for k, v in item_count_per_section.items()}

Output

{1: [0, 1, 2], 2: [3, 4, 5, 6, 7], 3: [8, 9], 4: [10, 11]}
like image 107
thefourtheye Avatar answered May 28 '26 08:05

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!