IT

리스트를 대략 같은 길이의 N 개 부분으로 나누기

lottoking 2020. 7. 3. 18:05
반응형

리스트를 대략 같은 길이의 N 개 부분으로 나누기


목록을 대략 동일한 부분 으로 나누는 가장 좋은 방법은 무엇입니까 ? 예를 들어,리스트에 7 개의 요소가 있고이를 2 개의 파트로 나누면 한 파트에 3 개의 요소를 가져오고 다른 하나에는 4 개의 요소가 있어야합니다.

내가 좋아하는 뭔가를 찾고 있어요 even_split(L, n)그 휴식 Ln부품.

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

위의 코드는 3 청크가 아닌 3 청크를 제공합니다. 나는 단순히 전치 (이 항목을 반복하고 각 열의 첫 번째 요소를 가져 와서 그 부분을 호출 한 다음 두 번째 부분을 넣고 두 번째 부분에 넣는 등) 할 수는 있지만 항목의 순서를 파괴합니다.


다음은 작동 할 수있는 것입니다.

def chunkIt(seq, num):
    avg = len(seq) / float(num)
    out = []
    last = 0.0

    while last < len(seq):
        out.append(seq[int(last):int(last + avg)])
        last += avg

    return out

테스트 :

>>> chunkIt(range(10), 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
>>> chunkIt(range(11), 3)
[[0, 1, 2], [3, 4, 5, 6], [7, 8, 9, 10]]
>>> chunkIt(range(12), 3)
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

간단히 목록 생성기로 쓸 수 있습니다.

def split(a, n):
    k, m = divmod(len(a), n)
    return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in xrange(n))

예:

>>> list(split(range(11), 3))
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10]]

연속 덩어리와 같은 바보 같은 것을 원하지 않는 한 :

>>> def chunkify(lst,n):
...     return [lst[i::n] for i in xrange(n)]
... 
>>> chunkify(range(13), 3)
[[0, 3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]]

이것은 * raison d' être 입니다 numpy.array_split:

>>> L
[0, 1, 2, 3, 4, 5, 6, 7]
>>> print(*np.array_split(L, 3))
[0 1 2] [3 4 5] [6 7]
>>> print(*np.array_split(range(10), 4))
[0 1 2] [3 4 5] [6 7] [8 9]

* 6 호실에서 제로 피레 우스 에게 신용


n청크 대신 청크 를 생성하도록 코드 변경 n:

def chunks(l, n):
    """ Yield n successive chunks from l.
    """
    newn = int(len(l) / n)
    for i in xrange(0, n-1):
        yield l[i*newn:i*newn+newn]
    yield l[n*newn-newn:]

l = range(56)
three_chunks = chunks (l, 3)
print three_chunks.next()
print three_chunks.next()
print three_chunks.next()

이것은 다음을 제공합니다.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
[18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]
[36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]

이것은 최종 그룹에 여분의 요소를 할당하지만 완벽하지는 않지만 "대략 N 동등한 부분"에 대한 귀하의 사양 내에 있습니다 :-) 따라서 56 요소가 (19,19,18)보다 낫다는 것을 의미합니다. (18,18,20).

다음 코드를 사용하여보다 균형 잡힌 출력을 얻을 수 있습니다.

#!/usr/bin/python
def chunks(l, n):
    """ Yield n successive chunks from l.
    """
    newn = int(1.0 * len(l) / n + 0.5)
    for i in xrange(0, n-1):
        yield l[i*newn:i*newn+newn]
    yield l[n*newn-newn:]

l = range(56)
three_chunks = chunks (l, 3)
print three_chunks.next()
print three_chunks.next()
print three_chunks.next()

어떤 출력 :

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
[19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37]
[38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]

n요소를 대략 k청크 나눈 경우 n % k다른 요소보다 청크 1 요소를 더 크게 만들어 추가 요소를 배포 할 수 있습니다.

다음 코드는 청크 길이를 제공합니다.

[(n // k) + (1 if i < (n % k) else 0) for i in range(k)]

예 : n=11, k=3결과[4, 4, 3]

그런 다음 청크의 시작 표시를 쉽게 계산할 수 있습니다.

[i * (n // k) + min(i, n % k) for i in range(k)]

예 : n=11, k=3결과[0, 4, 8]

i+1th 청크를 경계로 사용하면 len 이있는 i목록의 청크 ln

l[i * (n // k) + min(i, n % k):(i+1) * (n // k) + min(i+1, n % k)]

마지막 단계로 목록 이해를 사용하여 모든 청크에서 목록을 만듭니다.

[l[i * (n // k) + min(i, n % k):(i+1) * (n // k) + min(i+1, n % k)] for i in range(k)]

예 : n=11, k=3, l=range(n)결과[range(0, 4), range(4, 8), range(8, 11)]


다음은 None목록을 동일한 길이로 만들기 위해 추가 한 것입니다.

>>> from itertools import izip_longest
>>> def chunks(l, n):
    """ Yield n successive chunks from l. Pads extra spaces with None
    """
    return list(zip(*izip_longest(*[iter(l)]*n)))

>>> l=range(54)

>>> chunks(l,3)
[(0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51), (1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52), (2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53)]

>>> chunks(l,4)
[(0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52), (1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53), (2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50, None), (3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47, 51, None)]

>>> chunks(l,5)
[(0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50), (1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51), (2, 7, 12, 17, 22, 27, 32, 37, 42, 47, 52), (3, 8, 13, 18, 23, 28, 33, 38, 43, 48, 53), (4, 9, 14, 19, 24, 29, 34, 39, 44, 49, None)]

이것은 단일 표현식으로 분할을 수행합니다.

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

이 예의 목록은 크기가 18이며 ​​5 개 부분으로 나뉩니다. 부품의 크기는 하나 이상의 요소가 다릅니다.


참조 more_itertools.divide:

n = 2

[list(x) for x in mit.divide(n, range(5, 11))]
# [[5, 6, 7], [8, 9, 10]]

[list(x) for x in mit.divide(n, range(5, 12))]
# [[5, 6, 7, 8], [9, 10, 11]]

를 통해 설치하십시오 > pip install more_itertools.


numpy.split을 살펴 보십시오 .

>>> a = numpy.array([1,2,3,4])
>>> numpy.split(a, 2)
[array([1, 2]), array([3, 4])]

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 chunks(l, amount):
    if amount < 1:
        raise ValueError('amount must be positive integer')
    chunk_len = len(l) // amount
    leap_parts = len(l) % amount
    remainder = amount // 2  # make it symmetrical
    i = 0
    while i < len(l):
        remainder += leap_parts
        end_index = i + chunk_len
        if remainder >= amount:
            remainder -= amount
            end_index += 1
        yield l[i:end_index]
        i = end_index

생산

    >>> list(chunks([1, 2, 3, 4, 5, 6, 7], 3))
    [[1, 2], [3, 4, 5], [6, 7]]


양수 (정수)의 청크를 처리 할 수있는 생성기가 있습니다. 청크 수가 입력 목록 길이보다 크면 일부 청크가 비어 있습니다. 이 알고리즘은 짧은 청크와 긴 청크를 분리하지 않고 번갈아 사용합니다.

ragged_chunks함수 테스트를위한 코드도 포함 시켰습니다 .

''' Split a list into "ragged" chunks

    The size of each chunk is either the floor or ceiling of len(seq) / chunks

    chunks can be > len(seq), in which case there will be empty chunks

    Written by PM 2Ring 2017.03.30
'''

def ragged_chunks(seq, chunks):
    size = len(seq)
    start = 0
    for i in range(1, chunks + 1):
        stop = i * size // chunks
        yield seq[start:stop]
        start = stop

# test

def test_ragged_chunks(maxsize):
    for size in range(0, maxsize):
        seq = list(range(size))
        for chunks in range(1, size + 1):
            minwidth = size // chunks
            #ceiling division
            maxwidth = -(-size // chunks)
            a = list(ragged_chunks(seq, chunks))
            sizes = [len(u) for u in a]
            deltas = all(minwidth <= u <= maxwidth for u in sizes)
            assert all((sum(a, []) == seq, sum(sizes) == size, deltas))
    return True

if test_ragged_chunks(100):
    print('ok')

곱셈을 호출 로 내 보내서 약간 더 효율적으로 만들 수 range있지만 이전 버전이 더 읽기 쉽다고 생각합니다 (및 DRYer).

def ragged_chunks(seq, chunks):
    size = len(seq)
    start = 0
    for i in range(size, size * chunks + 1, size):
        stop = i // chunks
        yield seq[start:stop]
        start = stop

목록 이해 사용하기 :

def divide_list_to_chunks(list_, n):
    return [list_[start::n] for start in range(n)]

이해하기 쉬운 내 솔루션

def split_list(lst, n):
    splitted = []
    for i in reversed(range(1, n + 1)):
        split_point = len(lst)//i
        splitted.append(lst[:split_point])
        lst = lst[split_point:]
    return splitted

그리고이 페이지에서 가장 짧은 한 줄짜리 (내 여자가 쓴)

def split(l, n):
    return [l[int(i*len(l)/n):int((i+1)*len(l)/n-1)] for i in range(n)]

5 부분으로 나누고 싶다고 말하십시오.

p1, p2, p3, p4, p5 = np.split(df, 5)

또 다른 방법은 이와 같은 것입니다. 여기서 아이디어는 그룹화를 사용하는 것이지만 제거하는 것입니다 None. 이 경우 목록의 첫 부분에있는 요소로 구성된 'small_parts'와 목록의 뒷부분에있는 'larger_parts'가 있습니다. '큰 부분'의 길이는 len (small_parts) + 1입니다. x를 두 개의 다른 하위 부분으로 고려해야합니다.

from itertools import izip_longest

import numpy as np

def grouper(n, iterable, fillvalue=None): # This is grouper from itertools
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

def another_chunk(x,num):
    extra_ele = len(x)%num #gives number of parts that will have an extra element 
    small_part = int(np.floor(len(x)/num)) #gives number of elements in a small part

    new_x = list(grouper(small_part,x[:small_part*(num-extra_ele)]))
    new_x.extend(list(grouper(small_part+1,x[small_part*(num-extra_ele):])))

    return new_x

내가 설정 한 방법은 튜플 목록을 반환합니다.

>>> x = range(14)
>>> another_chunk(x,3)
[(0, 1, 2, 3), (4, 5, 6, 7, 8), (9, 10, 11, 12, 13)]
>>> another_chunk(x,4)
[(0, 1, 2), (3, 4, 5), (6, 7, 8, 9), (10, 11, 12, 13)]
>>> another_chunk(x,5)
[(0, 1), (2, 3, 4), (5, 6, 7), (8, 9, 10), (11, 12, 13)]
>>> 

다음은 "남은"요소를 모든 덩어리에 균등하게 퍼뜨리는 또 다른 변형입니다. 이 구현에서는 프로세스 시작시 더 큰 청크가 발생합니다.

def chunks(l, k):
  """ Yield k successive chunks from l."""
  if k < 1:
    yield []
    raise StopIteration
  n = len(l)
  avg = n/k
  remainders = n % k
  start, end = 0, avg
  while start < n:
    if remainders > 0:
      end = end + 1
      remainders = remainders - 1
    yield l[start:end]
    start, end = end, end+avg

예를 들어 14 개의 요소 목록에서 4 개의 청크를 생성하십시오.

>>> list(chunks(range(14), 4))
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10], [11, 12, 13]]
>>> map(len, list(chunks(range(14), 4)))
[4, 4, 3, 3]

직업의 답변 과 동일 하지만 청크 수보다 작은 크기의 목록을 고려합니다.

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

n (청크 수)이 7이고 lst (분할 목록)가 [1, 2, 3] 인 경우 청크는 [[0], [1] 대신 [[0], [1], [2]]입니다. ], [2], [], [], [], []]


다음을 사용할 수도 있습니다.

split=lambda x,n: x if not x else [x[:n]]+[split([] if not -(len(x)-n) else x[-(len(x)-n):],n)][0]

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

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

#!/usr/bin/python


first_names = ['Steve', 'Jane', 'Sara', 'Mary','Jack','Bob', 'Bily', 'Boni', 'Chris','Sori', 'Will', 'Won','Li']

def chunks(l, n):
for i in range(0, len(l), n):
    # Create an index range for l of n items:
    yield l[i:i+n]

result = list(chunks(first_names, 5))
print result

링크 에서 선택하면 이것이 도움이되었습니다. 미리 정의 된 목록이있었습니다.


이 경우 직접 코드를 작성했습니다.

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

split_ports (1, 10, 9)는

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

이 코드는 나를 위해 작동합니다 (Python3 호환).

def chunkify(tab, num):
    return [tab[i*num: i*num+num] for i in range(len(tab)//num+(1 if len(tab)%num else 0))]

예 ( 바이트 배열 유형의 경우 list 에서도 작동 합니다) :

b = bytearray(b'\x01\x02\x03\x04\x05\x06\x07\x08')
>>> chunkify(b,3)
[bytearray(b'\x01\x02\x03'), bytearray(b'\x04\x05\x06'), bytearray(b'\x07\x08')]
>>> chunkify(b,4)
[bytearray(b'\x01\x02\x03\x04'), bytearray(b'\x05\x06\x07\x08')]

이것은 길이 <= n,> = 0의 청크를 제공합니다.

데프

 chunkify(lst, n):
    num_chunks = int(math.ceil(len(lst) / float(n))) if n < len(lst) else 1
    return [lst[n*i:n*(i+1)] for i in range(num_chunks)]

예를 들어

>>> chunkify(range(11), 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]
>>> chunkify(range(11), 8)
[[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10]]

솔루션의 대부분을 시도했지만 내 경우에는 효과가 없었으므로 대부분의 경우와 모든 유형의 배열에서 작동하는 새로운 기능을 만듭니다.

import math

def chunkIt(seq, num):
    seqLen = len(seq)
    total_chunks = math.ceil(seqLen / num)
    items_per_chunk = num
    out = []
    last = 0

    while last < seqLen:
        out.append(seq[last:(last + items_per_chunk)])
        last += items_per_chunk

    return out

def evenly(l, n):
    len_ = len(l)
    split_size = len_ // n
    split_size = n if not split_size else split_size
    offsets = [i for i in range(0, len_, split_size)]
    return [l[offset:offset + split_size] for offset in offsets]

예:

l = [a for a in range(97)] 각 부분은 마지막 부분을 제외하고 9 개의 부분으로 이루어져 있습니다.

산출:

[[0, 1, 2, 3, 4, 5, 6, 7, 8],
 [9, 10, 11, 12, 13, 14, 15, 16, 17],
 [18, 19, 20, 21, 22, 23, 24, 25, 26],
 [27, 28, 29, 30, 31, 32, 33, 34, 35],
 [36, 37, 38, 39, 40, 41, 42, 43, 44],
 [45, 46, 47, 48, 49, 50, 51, 52, 53],
 [54, 55, 56, 57, 58, 59, 60, 61, 62],
 [63, 64, 65, 66, 67, 68, 69, 70, 71],
 [72, 73, 74, 75, 76, 77, 78, 79, 80],
 [81, 82, 83, 84, 85, 86, 87, 88, 89],
 [90, 91, 92, 93, 94, 95, 96]]

Rounding the linspace and using it as an index is an easier solution than what amit12690 proposes.

function chunks=chunkit(array,num)

index = round(linspace(0,size(array,2),num+1));

chunks = cell(1,num);

for x = 1:num
chunks{x} = array(:,index(x)+1:index(x+1));
end
end

참고URL : https://stackoverflow.com/questions/2130016/splitting-a-list-into-n-parts-of-approximately-equal-length

반응형