在项目开发的过程中,遇到分页的第一页就展示大量的数据,导致前端列表加载展示的速度慢,所以需要在本地加入分页处理,把所有数据先放到内存里,下面我用python演示如何实现本地分页的算法(针对二级数据结构)
initialsize = 2 # 首屏展示条数
eachsize = 5 # 剩余页展示条数
local_pages = [] # 本地分页数据
def makepage(d):
'''
制作分页数据
'''
local_pages.clear()
if calcsize(d) > initialsize: # 总条数大于首屏数,使用本地分页
sublist = []
for item in d:
for child in item["child"]:
sublist.append(child)
firstpagesize = min(len(sublist), initialsize) # 第一页的大小
local_pages.append(sublist[0:firstpagesize]) # 取第一页的集合
remain_size = len(sublist)-firstpagesize # 剩余条数
group_count = int(remain_size / eachsize) # 计算分页数
last_count = remain_size % eachsize # 取余,最后剩余多少条
idx = 0
for idx in range(group_count):
start = firstpagesize + idx * eachsize
end = start + eachsize
local_pages.append(sublist[start:end]) # 新增页集合
if last_count > 0:
local_pages.append(sublist[-last_count:]) # 余数不为0,将作为最后一页集合
pass
def calcsize(d)->int:
'''
计算总条数
'''
size = 0
for item in d:
size += len(item["child"]) + 1
return size
def printpage():
'''
打印页面
'''
idx = 0
for p in local_pages:
idx += 1
print("page:{}".format(idx))
for item in p:
print(item)
data = [{"id":"1",
"name":"parent_1",
"child":[
{"id":"1_1",
"name":"rs234326348264",
"parent_id":"1"
},
{"id":"1_2",
"name":"rs234326348264",
"parent_id":"1"
},
{"id":"1_3",
"name":"rs234326348264",
"parent_id":"1"
},
{"id":"1_4",
"name":"rs234326348264",
"parent_id":"1"
},
{"id":"1_5",
"name":"rs234326348264",
"parent_id":"1"
},
{"id":"1_6",
"name":"rs234326348264",
"parent_id":"1"
},
{"id":"1_7",
"name":"rs234326348264",
"parent_id":"1"
},
{"id":"1_8",
"name":"rs234326348264",
"parent_id":"1"
},
{"id":"1_9",
"name":"rs234326348264",
"parent_id":"1"
}]},
{"id":"2",
"name":"parent_2",
"child":[
{"id":"2_1",
"name":"rs234326348264",
"parent_id":"2"
}]}]
print(f"首屏展示条数:{initialsize}")
print(f"剩余页展示条数:{eachsize}")
makepage(data)
printpage()
打印结果
首屏展示条数:2
剩余页展示条数:5
page:1
{'id': '1_1', 'name': 'rs234326348264', 'parent_id': '1'}
{'id': '1_2', 'name': 'rs234326348264', 'parent_id': '1'}
page:2
{'id': '1_3', 'name': 'rs234326348264', 'parent_id': '1'}
{'id': '1_4', 'name': 'rs234326348264', 'parent_id': '1'}
{'id': '1_5', 'name': 'rs234326348264', 'parent_id': '1'}
{'id': '1_6', 'name': 'rs234326348264', 'parent_id': '1'}
{'id': '1_7', 'name': 'rs234326348264', 'parent_id': '1'}
page:3
{'id': '1_8', 'name': 'rs234326348264', 'parent_id': '1'}
{'id': '1_9', 'name': 'rs234326348264', 'parent_id': '1'}
{'id': '2_1', 'name': 'rs234326348264', 'parent_id': '2'}
到此这篇关于一文教你使用python实现本地分页的文章就介绍到这了,更多相关python本地分页内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论