切片列表到有序的块

时间:2014-02-12 01:23:42

标签: python list slice

我有词典:

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 个答案:

答案 0 :(得分: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]}

答案 1 :(得分:2)

理解iter的{​​{3}} 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的答案