python實現資料分頁小練習

MHyourh發表於2020-11-05

非函式式:

data_list = []
for i in range(1,901):
    data_list.append('豆谷雲-%s' % i)

while True:

    # 1.你要檢視的頁碼
    page = int(input("請輸入你要檢視的頁碼:"))

    # 2.每頁顯示多少條資料
    per_page_num = 10

    # 3.定義每頁開始位置和結束位置
    start = (page - 1) * per_page_num
    end = page * per_page_num

    page_data_list = data_list[start:end]
    for item in page_data_list:
        print(item)

物件導向:

'''
遇到問題沒人解答?小編建立了一個Python學習交流QQ群:778463939
尋找有志同道合的小夥伴,互幫互助,群裡還有不錯的視訊學習教程和PDF電子書!
'''
class Pagenation(object):

    def __init__(self,data_list,page,per_data_num = 10):
        '''
        初始化
        :param data_list: 所有資料列表
        :param page: 當前要檢視的列表頁
        :param per_data_num: 每頁預設要顯示幾條
        '''
        self.data_list = data_list
        self.page = page
        self.per_data_num = per_data_num

    @property
    def start(self):
        '''
        計算引索的起始位置
        :return:
        '''
        return (self.page - 1) * self.per_data_num

    @property
    def end(self):
        '''
        計算引索的結束位置
        :return:
        '''
        return self.page * self.per_data_num

    def show(self):
        '''
        切片取資料,展示對應分頁的結果
        :return:
        '''
        result = self.data_list[self.start:self.end]
        for row in result:
            print(row)

data_list = []
for i in range(1,901):
    data_list.append('豆谷雲-%s' % i)

while True:

    # 1.輸入要檢視的頁碼
    page = int(input("請輸入要檢視的頁碼:"))

    obj = Pagenation(data_list,page)

    obj.show()

相關文章