将可切片的对象成批剪切(如用于在网站上分页显示)
Batcher的Python项目详细描述
将任何可切片对象拆分成批:
>>> from batcher import Batcher >>> items = list('ABCDEFGHIJ') >>> batcher = Batcher(items, 4) >>> # How many batches are available? >>> len(batcher) 3 >>> # Get contents of the first batch >>> list(batcher[0]) ['A', 'B', 'C', 'D']
批处理看起来像列表,但也知道它们的上下文:
>>> batch = batcher[1] >>> batch <Batch #1> >>> batcher[1].previous <Batch #0> >>> batcher[1].next <Batch #2> >>> batcher[2].next None
web应用程序中的一个常见需求是实现寻呼机小部件。 当用户查看页面n并且我们希望 显示以n为中心的页面范围,调整端点以保持 它们在范围内:
>>> items = range(100) >>> batcher = Batcher(items, 4) >>> len(batcher) 25 >>> # The range of 5 batches centered on the given batch >>> batcher[0].range(5) [<Batch #0>, <Batch #1>, <Batch #2>, <Batch #3>, <Batch #4>] >>> batcher[7].range(5) [<Batch #5>, <Batch #6>, <Batch #7>, <Batch #8>, <Batch #9>] >>> batcher[23].range(5) [<Batch #20>, <Batch #21>, <Batch #22>, <Batch #23>, <Batch #24>]
如果没有足够的可用批次,则返回整个批次:
>>> items = range(10) >>> batcher = Batcher(items, 4) >>> len(batcher) 3 >>> batcher[1].range(5) [<Batch #0>, <Batch #1>, <Batch #2>]
因为批处理使用python的切片api来检索数据,所以我们可以 查询slice对象以找出第一个和最后一个的索引 批量项目,用于显示数据,如“第1页(项目1-10)”:
>>> items = range(25) >>> batcher = Batcher(items, 10) >>> batch = batcher[0] >>> batch.slice slice(0, 10, None) >>> "Page %d (items %d-%d)" % (batch.index + 1, ... batch.slice.start + 1, ... batch.slice.stop) 'Page 1 (items 1-10)'
注意python的切片语义意味着索引是基于零的(所以 我们在格式化显示时添加1),并且切片的停止索引 指向系列结束后的项。