O‘REILLY: Chunk —— 分割列表

tech2022-07-09  173

CheckIO是一个通过闯关游戏学习编程的网站(Python和JavaScript)。通过解题开发新“岛屿”,同时,通过做任务获得Quest Points解锁会员题目。 文章内容:题目、我自己的思路和代码以及优秀代码,如果想看大神解题可以直接跳到“优秀代码”部分。 本题链接:https://py.checkio.org/en/mission/chunk/

题目

将列表分割成相同大小的小列表,最后一个小列表可以小于默认的大小。 如果原列表为空,那么就不需分割。 输入: 两个参数,列表和分割大小

输出: 包含分割后列表的数组

举个栗子:

chunking_by([5, 4, 7, 3, 4, 5, 4], 3) == [[5, 4, 7], [3, 4, 5], [4]] chunking_by([3, 4, 5], 1) == [[3], [4], [5]]

假设: 分割后的大小 > 0

难度: Elementary+

题目框架

from typing import Iterable def chunking_by(items, size): # your code here return None if __name__ == '__main__': print("Example:") print(list(chunking_by([5, 4, 7, 3, 4, 5, 4], 3))) # These "asserts" are used for self-checking and not for an auto-testing assert list(chunking_by([5, 4, 7, 3, 4, 5, 4], 3)) == [[5, 4, 7], [3, 4, 5], [4]] assert list(chunking_by([3, 4, 5], 1)) == [[3], [4], [5]] assert list(chunking_by([5, 4], 7)) == [[5, 4]] assert list(chunking_by([], 3)) == [] assert list(chunking_by([4, 4, 4, 4], 4)) == [[4, 4, 4, 4]] print("Coding complete? Click 'Check' to earn cool rewards!")

思路及代码

思路

增加新变量 count,计算结果列表长度;用 count 和 size 变量控制每次截取子列表的开始和位置;将截取获得的列表增加到 result 变量里。

代码

def chunking_by(items, size): result = [] # 保存结果 count = len(items) // size if len(items) % size == 0 else len(items) // size + 1 if items: for i in range(count): result.append(items[i*size: (i+1)*size]) return result

优秀代码

No.1

def chunking_by(items: list, size: int) -> Iterable: result = [items[i: i + size] for i in range(0, len(items), size)] return result

可以直接用 range 控制 i 的步长为 size

No.2

def chunking_by(items: list, size: int) -> Iterable: len_items = len(items) for i in range(0, len_items, size): left = i right = min(left + size, len_items) yield items[left:right] return items

这里用 left 和 left + size 控制截取的部分

最新回复(0)