python将一个列表平均分成几份(完美解决)

话不多说直接上代码,可以直接复制运行

def bisector_list(tabulation:list,num:int):
    """
    将列表平均分成几份
    :param tabulation: 列表
    :param num: 份数
    :return: 返回一个新的列表
    """
    new_list = []

    '''列表长度大于等于份数'''
    if len(tabulation)>=num:
        '''remainder:列表长度除以份数,取余'''
        remainder = len(tabulation)%num
        if remainder == 0:
            '''merchant:列表长度除以分数'''
            merchant = int(len(tabulation) / num)
            '''将列表平均拆分'''
            for i in range(1,num+1):
                if i == 1:
                    new_list.append(tabulation[:merchant])
                else:
                    new_list.append(tabulation[(i-1)*merchant:i*merchant])
            return new_list
        else:
            '''merchant:列表长度除以分数 取商'''
            merchant = int(len(tabulation)//num)
            '''remainder:列表长度除以份数,取余'''
            remainder = int(len(tabulation) % num)
            '''将列表平均拆分'''
            for i in range(1, num + 1):
                if i == 1:
                    new_list.append(tabulation[:merchant])
                else:
                    new_list.append(tabulation[(i - 1) * merchant:i * merchant])
                    '''将剩余数据的添加前面列表中'''
                    if int(len(tabulation)-i*merchant)<=merchant:
                        for j in tabulation[-remainder:]:
                            new_list[tabulation[-remainder:].index(j)].append(j)
            return new_list
    else:
        '''如果列表长度小于份数'''
        for i in range(1, len(tabulation) + 1):
            tabulation_subset = []
            tabulation_subset.append(tabulation[i - 1])
            new_list.append(tabulation_subset)
        return new_list

if __name__ == '__main__':
    a = [1,2,3,4,5,6,7,8,9]
    x = bisector_list(a,4)
    print(x)

你可能感兴趣的:(python基础,python,列表,算法,数据结构)