将列表分割成有序的块

3

I have dictionary like:

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

这个字典中检索到的项目总数为:

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

现在我想按照字典的值来转换total_items
items_no_per_section = {1: [0,1,2], 2: [3,4,5,6,7], 3:[8,9], 4:[10,11] }

例如,将total_items序列逐个切片为子列表,这些子列表从先前的“迭代”索引开始,并以初始字典中的value结束。

2个回答

2

您根本不需要找到 total_items。您可以直接使用 itertools.countitertools.islice 和字典推导式,像这样:

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()}

输出

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

2

使用itertools.islice的字典推导式,对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()}

输出:

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

注意:这适用于任何total_items,不仅仅是range(sum(values)),假设这只是你为了让问题更通用而提供的示例。如果您只想要数字,请使用@thefourtheye的答案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接