将列表拆分为块索引列表

时间:2016-04-21 14:48:05

标签: python list

假设我有一个这样的列表:

myList=['A','B','C','D','E','F','G','H','I','J','K']

因此,假设我想将此列表作为n批处理。如果是n = 3, 我想要一个名为batchIdx [(0,3),(4,7),(8,10)]的列表,其中每个元组都指向myList的(start,end)索引。

myList可以是可变长度的。这不仅仅是将列表分成相同大小的块。就像使用divmod()

编辑:我实际上想创建一个索引到myList的列表。我会在程序的不同部分使用这些索引。

实施此方法的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

根据问题编辑更新了答案:

  

这不仅仅是将列表分成相同大小的块。就像使用divmod()

一样

这是我的解决方案,它返回索引,将长度l的列表分成n个批次:

def slice_indices(l, n):
    q, r = divmod(l, n)
    step = q + 1 if r else q
    return [(i, min(i+step, l)) for i in range(0, l, step)]

让我们先看一些指数:

>>> slice_indices(l=11, n=3)
[(0, 4), (4, 8), (8, 11)]
# We get 3 batches, index covers [0, 11] so we pass.

>>> slice_indices(l=30, n=4)
[(0, 8), (8, 16), (16, 24), (24, 30)]
# We get 4 batches, and index covers [0, 30], so we pass.

让我们看一下你的列表索引:

>>> [myList[slice(*s)] for s in slice_indices(l=11, n=3)]
[['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K']]

并且不会突破n = 1n = l

的限制
>>> [myList[slice(*s)] for s in slice_indices(l=11, n=1)]
[['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']] # 1 batch
>>> [myList[slice(*s)] for s in slice_indices(l=11, n=11)]
[['A'], ['B'], ['C'], ['D'], ['E'], ['F'], ['G'], ['H'], ['I'], ['J'], ['K']] # 11 batches

答案 1 :(得分:0)

Shell ("("my application.exe")
sendkeys.send = ("o")
sendkeys.send = ("p")
sendkeys.send = ("e")
sendkeys.send = ("n")
sendkeys.send = ("{ENTER}")
相关问题