【问题标题】:Slice list to ordered chunks切片列表到有序块
【发布时间】:2014-02-12 01:23:42
【问题描述】:

我有这样的字典:

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 结束的子列表。

【问题讨论】:

    标签: python list slice


    【解决方案1】:

    您根本不需要找到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.isliced itertotal_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 的答案

      【讨论】:

        猜你喜欢
        • 2010-12-14
        • 1970-01-01
        • 2021-03-14
        • 1970-01-01
        • 1970-01-01
        • 2017-06-24
        • 2015-02-19
        • 2014-05-13
        • 1970-01-01
        相关资源
        最近更新 更多