将清单大致等份的最佳方法是什么?例如,如果列表有7个元素,并将其分为2部分,我们希望其中一部分有3个元素,而另一部分应该有4个元素。

我正在寻找类似even_split(L, n)的东西,它将L分解为n部分。

def chunks(L, n):
    """ Yield successive n-sized chunks from L.
    """
    for i in range(0, len(L), n):
        yield L[i:i+n]

上面的代码给出了3个块,而不是3个块。我可以简单地转置(遍历这个,取每列的第一个元素,称之为第一部分,然后取第二个元素,把它放在第二部分,等等),但这破坏了项目的顺序。


当前回答

这将通过一个表达式将其拆分为相等的部分,同时保持顺序:

myList = list(range(18))  # given list
N = 5  # desired number of parts

[myList[(i*len(myList))//N:((i+1)*len(myList))//N] for i in range(N)]
# [[0, 1, 2], [3, 4, 5, 6], [7, 8, 9], [10, 11, 12, 13], [14, 15, 16, 17]]

各部分的差异不超过一个元素。把18分成5份,结果是3 + 4 + 3 + 4 + 4 = 18。

其他回答

这里有一个单独的函数,它处理了大多数不同的分裂情况:

def splitList(lst, into):
    '''Split a list into parts.

    :Parameters:
        into (str) = Split the list into parts defined by the following:
            '<n>parts' - Split the list into n parts.
                ex. 2 returns:  [[1, 2, 3, 5], [7, 8, 9]] from [1,2,3,5,7,8,9]
            '<n>parts+' - Split the list into n equal parts with any trailing remainder.
                ex. 2 returns:  [[1, 2, 3], [5, 7, 8], [9]] from [1,2,3,5,7,8,9]
            '<n>chunks' - Split into sublists of n size.
                ex. 2 returns: [[1,2], [3,5], [7,8], [9]] from [1,2,3,5,7,8,9]
            'contiguous' - The list will be split by contiguous numerical values.
                ex. 'contiguous' returns: [[1,2,3], [5], [7,8,9]] from [1,2,3,5,7,8,9]
            'range' - The values of 'contiguous' will be limited to the high and low end of each range.
                ex. 'range' returns: [[1,3], [5], [7,9]] from [1,2,3,5,7,8,9]
    :Return:
        (list)
    '''
    from string import digits, ascii_letters, punctuation
    mode = into.lower().lstrip(digits)
    digit = into.strip(ascii_letters+punctuation)
    n = int(digit) if digit else None

    if n:
        if mode=='parts':
            n = len(lst)*-1 // n*-1 #ceil
        elif mode=='parts+':
            n = len(lst) // n
        return [lst[i:i+n] for i in range(0, len(lst), n)]

    elif mode=='contiguous' or mode=='range':
        from itertools import groupby
        from operator import itemgetter

        try:
            contiguous = [list(map(itemgetter(1), g)) for k, g in groupby(enumerate(lst), lambda x: int(x[0])-int(x[1]))]
        except ValueError as error:
            print ('{} in splitList\n   # Error: {} #\n {}'.format(__file__, error, lst))
            return lst
        if mode=='range':
            return [[i[0], i[-1]] if len(i)>1 else (i) for i in contiguous]
        return contiguous

r = splitList([1, '2', 3, 5, '7', 8, 9], into='2parts')
print (r) #returns: [[1, '2', 3, 5], ['7', 8, 9]]

使用numpy实现。linspace方法。

只需指定要将数组分成的部分的数量。各部门的规模将几乎相同。

例子:

import numpy as np   
a=np.arange(10)
print "Input array:",a 
parts=3
i=np.linspace(np.min(a),np.max(a)+1,parts+1)
i=np.array(i,dtype='uint16') # Indices should be floats
split_arr=[]
for ind in range(i.size-1):
    split_arr.append(a[i[ind]:i[ind+1]]
print "Array split in to %d parts : "%(parts),split_arr

给:

Input array: [0 1 2 3 4 5 6 7 8 9]
Array split in to 3 parts :  [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8, 9])]

在这种情况下,我自己编写了代码:

def chunk_ports(port_start, port_end, portions):
    if port_end < port_start:
        return None

    total = port_end - port_start + 1

    fractions = int(math.floor(float(total) / portions))

    results = []

    # No enough to chuck.
    if fractions < 1:
        return None

    # Reverse, so any additional items would be in the first range.
    _e = port_end
    for i in range(portions, 0, -1):
        print "i", i

        if i == 1:
            _s = port_start
        else:
            _s = _e - fractions + 1

        results.append((_s, _e))

        _e = _s - 1

    results.reverse()

    return results

Divide_ports(1,10,9)将返回

[(1, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10)]

与job的答案相同,但考虑了大小小于块数量的列表。

def chunkify(lst,n):
    [ lst[i::n] for i in xrange(n if n < len(lst) else len(lst)) ]

如果n (chunk的数量)是7,LST(要分割的列表)是[1,2,3],则chunk为[[0],[1],[2]],而不是[[0],[1],[2],[],[],[],[],[]]

假设你想把一个列表[1、2、3、4、5、6、7、8]分成3个元素列表

如[[1,2,3],[4,5,6],[7,8]],如果剩下的最后一个元素小于3,则将它们分组在一起。

my_list = [1, 2, 3, 4, 5, 6, 7, 8]
my_list2 = [my_list[i:i+3] for i in range(0, len(my_list), 3)]
print(my_list2)

输出:[[1,2,3],[4,5,6],[7,8]]

其中一部分的长度为3。用你自己的块大小替换3。