一、目标
用尽量简短的代码将单个列表拆成多个列表
二、实现需求需先了解两个小知识(可略过)
- math模块的ceil(x)函数
ceil(x)返回取大于或者等于x的最小整数。
>>> from math import ceil
>>> num = ceil(5 / 2)
>>> num
3
- map函数
是指根据提供的函数对指定序列做映射。
语法:map(function, iterable, …)
>>> lst = list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))
>>> lst
[1, 4, 9, 16, 25]
上例map函数的功能是将列表的的每个元素取出,放入函数中进行计算,返回<map object at 0x000001F96BF536C8>对象。
三、具体实现代码
from math import ceil
lst = [1, 2, 3, 4, 5]
def test(lst, num):
return list(map(lambda x: lst[x * num : x * num + num], list(range(0, ceil(len(lst) / num)))))
print(test(lst, 2))
运行结果
[[1, 2], [3, 4], [5]]