gpt4 book ai didi

python - 如何使用给定列表创建分页功能

转载 作者:行者123 更新时间:2023-12-04 13:09:23 25 4
gpt4 key购买 nike

我必须创建一个分页函数,要求 2 个参数、一个数组和一个 page_number。
我试图解决列表中的任何项目,但我遇到了一些问题。
这是我的代码:

def paginator(array,page_number):
if 0 < page_number < len(array):
obj_per_page = len(array)//page_number
objects = len(array)
count = 0
start = 0
while objects > 1:
count += 1
objects -= len(array)//page_number
object_available = array[start:obj_per_page]
print(f'this is page {count} have object {object_available}')
start = obj_per_page
obj_per_page += len(array)//page_number

elif len(array) <= page_number:
for i in array:
print(f'thi is page {i} have object [{i}]')

else:
print(array)


list = [1,2,3,4,5,6]
page_number = 3

paginator(list,page_number)
output
this is page 1 have object [1, 2]
this is page 2 have object [3, 4]
this is page 3 have object [5, 6]
`此代码仅在以下情况下提供预期的输出
如果 len(list) 可以被 page_number 整除
如果 page_number 为 0 或 1
如果 page_number 大于等于 len(list)`
错误
假设 len(list) 是 9 并且 page_number 是 (2,4,5,6,7,8) 之一
9 % (2,4,5,6,7,8) 的余数是 (1,1,4,3,2,1) ,所以缺少的项数等于余数 what i want如果 len(list) 是 9 并且 page_number 是 4 并且我想要输出类似的东西
this is page 1 have object [1, 2, 3]
this is page 2 have object [4, 5]
this is page 3 have object [6, 7]
this is page 4 have object [8, 9]
如果你们有其他解决方案,请帮助我分享
我试着解释我的问题,对不起,语法不好

最佳答案

def paginator(array, page_number):
n, remainder = page_number, len(array) % page_number
curr, idx, old_idx = 1, 0, 0
while n + remainder != 0:
idx += len(array) // page_number + bool(remainder)
print(f"this is page {curr} have object {array[old_idx:idx]}")
n -= 1
remainder = max(remainder - 1, 0)
curr += 1
old_idx = idx


lst = list(range(1, 10))
page_number = 4

paginator(lst, page_number)
打印:
this is page 1 have object [1, 2, 3]
this is page 2 have object [4, 5]
this is page 3 have object [6, 7]
this is page 4 have object [8, 9]

关于python - 如何使用给定列表创建分页功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67254840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com