首页 > 技术文章 > python学习day3(练习切片取值、传参)

grace-l 2020-05-24 23:37 原文

练习:

chunk([1,2,3,4,5],2) =>[[1,2],[3,4],[5]]

 

知识点:

1、

 

思路:

切片取值,注意测试多次,使其满足此类型计算

 

方法一:

"""
Chunk([1,2,3,4,5],2)=> [[1,2],[3,4],[5]]

"""
def chunk(lst,size):
    result = []
    i = 0
    while (i < len(lst)):
        if i + size > len(lst):
            result.append(lst[i: len(lst) + 1])
        else:
            result.append(lst[i:i + size])
        i += size
    print(result)
chunk([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)

  

方法二:

from math import ceil
def chunk(lst,size):
    return list(
        map(lambda x: lst[x * size :x * size+size],
            list(range(0,ceil(len(lst)/size)))))
print(chunk([1,2,3,4,5],2))

  

推荐阅读