这是您的分页方式,还是有更好的算法? [英] Is this how you paginate, or is there a better algorithm?

查看:91
本文介绍了这是您的分页方式,还是有更好的算法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够采用类似的顺序:

I want to be able to take a sequence like:

my_sequence = ['foo', 'bar', 'baz', 'spam', 'eggs', 'cheese', 'yogurt']

使用类似的功能:

my_paginated_sequence = get_rows(my_sequence, 3)

获得:

[['foo', 'bar', 'baz'], ['spam', 'eggs', 'cheese'], ['yogurt']]

这是我通过仔细考虑才想到的:

This is what I came up with by just thinking through it:

def get_rows(sequence, num):
    count = 1
    rows = list()
    cols = list()
    for item in sequence:
        if count == num:
            cols.append(item)
            rows.append(cols)
            cols = list()
            count = 1
        else:
            cols.append(item)
            count += 1
    if count > 0:
        rows.append(cols)
    return rows

推荐答案

如果您知道自己有可分割的序列(列表或元组),

If you know you have a sliceable sequence (list or tuple),

def getrows_byslice(seq, rowlen):
    for start in xrange(0, len(seq), rowlen):
        yield seq[start:start+rowlen]

这当然是生成器,因此,如果您绝对需要列表作为结果,则可以使用list(getrows_byslice(seq, 3))等.

This of course is a generator, so if you absolutely need a list as the result, you'll use list(getrows_byslice(seq, 3)) or the like, of course.

如果您开始使用的是通用的迭代器,则 itertools食谱 grouper配方的帮助...:

If what you start with is a generic iterable, the itertools recipes offer help with the grouper recipe...:

import itertools

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

(同样,如果需要列表,则需要在此调用list).

(again, you'll need to call list on this if a list is what you want, of course).

由于您实际上希望最后一个元组被截断而不是填充,因此您需要修剪"最后一个元组的尾随填充值.

Since you actually want the last tuple to be truncated rather than filled up, you'll need to "trim" the trailing fill-values from the very last tuple.

这篇关于这是您的分页方式,还是有更好的算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆