2014-02-12 67 views
2

我有字典,如:切片列表排序块

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

iee切片total_items按顺序排列以从先前的“迭代”索引开始并从最初的字典结束于value

回答

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

输出的itertools.isliceditertotal_items

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

字典理解:

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)),假设只是你的样品,以保持通用的问题。如果你只是想要的数字,去@fourtheye的回答