python 自定義資料分頁

二月雪發表於2024-11-20
def paginate_data(data_list, size_page, current_page):
    """
    資料分頁函式

    :param data_list: list, 資料列表
    :param size_page: int, 每頁的數量
    :param current_page: int, 當前頁碼
    :return: tuple, (總頁數, 當前頁碼, 當前頁的資料列表)
    """
    if size_page <= 0:
        raise ValueError("每頁數量必須大於0")
    if current_page <= 0:
        raise ValueError("當前頁碼必須大於0")

    # 計算總頁數
    total_page = (len(data_list) + size_page - 1) // size_page

    # 校正當前頁碼
    current_page = min(current_page, total_page)

    # 計算當前頁資料的起始索引和結束索引
    start_index = (current_page - 1) * size_page
    end_index = start_index + size_page

    # 獲取當前頁的資料列表
    result_data_list = data_list[start_index:end_index]

    return total_page, current_page, result_data_list

# 示例用法
data_list = [i for i in range(100)]  # 0到99的數
size_page = 10
current_page = 3

total_page, current_page, result_data_list = paginate_data(data_list, size_page, current_page)

print(f"總頁數: {total_page}")
print(f"當前頁: {current_page}")
print(f"當前頁資料列表: {result_data_list}")

相關文章