简体   繁体   English

切片列表到有序块

[英]Slice list to ordered chunks

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: 现在,我想按以下方式通过字典的值转换total_items

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

Ie slice total_items sequencially to sublists which startrs from previous "iteration" index and finished with value from initial dictionary. 即切片total_items sequencially到从前面的“迭代”索引startrs并与完成子列表value从初始字典。

You don't need to find total_items at all. 您根本不需要找到total_items You can straightaway use itertools.count , itertools.islice and dictionary comprehension, like this 您可以像这样直接使用itertools.countitertools.islice和Dictionary理解。

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

dict comprehension of itertools.islice d iter of total_items : itertools.islicetotal_items iter total_items

from itertools import islice
item_count_per_section = {1: 3, 2: 5, 3: 2, 4: 2}
total_items = range(sum(item_count_per_section.values()))

i = iter(total_items)
{key: list(islice(i, value)) for key, value in item_count_per_section.items()}

Outputs: 输出:

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

Note: this works for any total_items , not just range(sum(values)) , assuming that was just your sample to keep the question generic. 注意:这适用于所有total_items ,而不只是range(sum(values)) ,假设这只是使问题通用的示例。 If you do just want the numbers, go with @thefourtheye's answer 如果您只想要数字,请使用@thefourtheye的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM