0

我正在尝试提出一种算法来通过分页遍历列表。

我只对初始索引和“页面”的大小感兴趣。

例如,如果我的列表长度为 100 项,并且页面长度为 10:

1st page:  starts at 0, length 10
2nd page:  starts at 11, length 10
3rd page:  starts at 21, length 10
...
Nth page:  starts at 90, length 10

我的问题是提出一个优雅的解决方案来满足这些情况:

1. list has 9 elements, page length is 10

       1st page:  starts at 0, length 9

2. list has 84 elements, page length is 10

      1st page:  starts at 0, length 10
      2nd page:  starts at 11, length 10
      3rd page:  starts at 21, length 10
      ...
      Nth page:  starts at 80, length 4

我可以用一堆条件和模运算来做到这一点,但我想知道是否有人可以为这个问题提供更好/优雅的方法。

谢谢!

4

1 回答 1

1

后面有一些代码在 Python 中完成了很长的路要走,也可以用于其他语言;其次是中级 Pythoneer 如何以更可维护的方式完成它:

>>> from pprint import pprint as pp
>>> n, perpage = 84, 10
>>> mylist = list(range(n))
>>> mylist[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> mylist[-10:] # last ten items
[74, 75, 76, 77, 78, 79, 80, 81, 82, 83]
>>> sublists = []
>>> for i in range(n):
    pagenum, offset = divmod(i, perpage)
    if offset == 0:
        # first in new page so create another sublist
        sublists.append([])
    # add item to end of last sublist
    sublists[pagenum].append(i)


>>> pp(sublists)
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
 [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
 [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
 [70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
 [80, 81, 82, 83]]
>>> # Alternatively
>>> sublists2 = [mylist[i:i+perpage] for i in range(0, n, perpage)]
>>> pp(sublists2)
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
 [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
 [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
 [70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
 [80, 81, 82, 83]]
>>> 
于 2013-05-02T06:27:10.047 回答