分页函数(Python)

2023-01-31 04:01:22 python 函数 分页
# coding=utf-8
def get_page(m, n):
    cur_page = n
    pages = []

    if cur_page <= 6:    # 百度分页为例
        limit_start = 1       # 起始页
    else:
        limit_start = cur_page-5

    if m >= cur_page+4:

        if cur_page < 6:
            limit_end = m-limit_start
        else:
            limit_end = cur_page + 4

    else:
        limit_end = m
        if cur_page >= 10:
            limit_start = limit_end-9

    for i in xrange(limit_start, limit_end+1):    # 这才是分页的关键

        if cur_page == i:
            pages.append(cur_page)
        else:
            pages.append(i)

    return pages

进一步精简代码:

# coding=utf-8
PER_PRE_NUM = 6
PER_NUMBER_MAX = 10


def get_page(m, n):
    cur_page = n
    limit_start = 1 if cur_page <= PER_PRE_NUM else cur_page - (PER_PRE_NUM-1)
    if m >= cur_page+(PER_PRE_NUM-2):
        limit_end = m - limit_start if cur_page < PER_PRE_NUM else cur_page + (PER_PRE_NUM-2)
    else:
        limit_end = m
        if cur_page >= PER_NUMBER_MAX:
            limit_start = limit_end-(PER_NUMBER_MAX-1)
    return [i for i in xrange(limit_start, limit_end+1)]

测试

assert get_page(7, 5) == [1, 2, 3, 4, 5, 6, 7]
assert get_page(12, 6) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
assert get_page(12, 7) == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
assert get_page(11, 3) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
assert get_page(11, 6) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
assert get_page(11, 7) == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
assert get_page(100, 99) == [91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
print(get_page(11, 1))
print(get_page(76, 25))
print(get_page(100, 50))

# coding=utf-8

PER_PRE_NUM = 6
PER_NUMBER_MAX = 10

# 百度分页为例
def get_page(m, n):
    cur_page = n  # 当前页
    if m > PER_NUMBER_MAX:
        limit_start = 1 if cur_page <= PER_PRE_NUM else cur_page - (PER_PRE_NUM - 1)

        if m >= cur_page+(PER_PRE_NUM-2):
            if n >= PER_PRE_NUM:
                limit_end = m - limit_start if cur_page < PER_PRE_NUM else cur_page + (PER_PRE_NUM - 2)
            else:
                limit_end = PER_NUMBER_MAX
        else:
            limit_end = m
            if cur_page >= PER_NUMBER_MAX or ((limit_end - limit_start) < PER_NUMBER_MAX):
                limit_start = limit_end - (PER_NUMBER_MAX - 1)

    else:
        limit_start, limit_end = 1, m

    return [i for i in xrange(limit_start, limit_end + 1)]


print(get_page(7, 5))
assert get_page(7, 5) == [1, 2, 3, 4, 5, 6, 7]
assert get_page(12, 6) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
assert get_page(12, 7) == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
assert get_page(11, 3) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
assert get_page(11, 6) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
assert get_page(11, 7) == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
assert get_page(100, 99) == [91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
print(get_page(11, 1))
print(get_page(76, 25))
print(get_page(18, 2))
print(get_page(11, 8))
print(get_page(11, 7))



相关文章