Programming

목록을 더 작은 목록으로 나누기 (반으로 분할)

procodes 2020. 7. 5. 21:21
반응형

목록을 더 작은 목록으로 나누기 (반으로 분할)


파이썬 목록을 쉽게 반으로 나눌 수있는 방법을 찾고 있습니다.

그래서 배열이 있다면 :

A = [0,1,2,3,4,5]

나는 얻을 수있을 것입니다 :

B = [0,1,2]

C = [3,4,5]

A = [1,2,3,4,5,6]
B = A[:len(A)//2]
C = A[len(A)//2:]

기능을 원한다면 :

def split_list(a_list):
    half = len(a_list)//2
    return a_list[:half], a_list[half:]

A = [1,2,3,4,5,6]
B, C = split_list(A)

좀 더 일반적인 해결책 ( '반으로 나누지 않고 원하는 부분 수를 지정할 수 있습니다) :

편집 : 홀수 목록 길이를 처리하도록 게시물이 업데이트되었습니다.

EDIT2 : Brians 유익한 의견에 따라 게시물을 다시 업데이트하십시오.

def split_list(alist, wanted_parts=1):
    length = len(alist)
    return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts] 
             for i in range(wanted_parts) ]

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

print split_list(A, wanted_parts=1)
print split_list(A, wanted_parts=2)
print split_list(A, wanted_parts=8)

f = lambda A, n=3: [A[i:i+n] for i in range(0, len(A), n)]
f(A)

n -사전 정의 된 길이의 결과 배열


def split(arr, size):
     arrs = []
     while len(arr) > size:
         pice = arr[:size]
         arrs.append(pice)
         arr   = arr[size:]
     arrs.append(arr)
     return arrs

테스트:

x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print(split(x, 5))

결과:

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13]]

B,C=A[:len(A)/2],A[len(A)/2:]


다음은 일반적인 해결책입니다. arr을 카운트 부분으로 나눕니다.

def split(arr, count):
     return [arr[i::count] for i in range(count)]

주문에 신경 쓰지 않으면 ...

def split(list):  
    return list[::2], list[1::2]

list[::2]0 번째 요소부터 시작하여 목록의 모든 두 번째 요소를 가져옵니다.
list[1::2]목록에서 첫 번째 요소부터 시작하여 매 초마다 요소를 가져옵니다.


def splitter(A):
    B = A[0:len(A)//2]
    C = A[len(A)//2:]

 return (B,C)

I tested, and the double slash is required to force int division in python 3. My original post was correct, although wysiwyg broke in Opera, for some reason.


There is an official Python receipe for the more generalized case of splitting an array into smaller arrays of size n.

from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

This code snippet is from the python itertools doc page.


Using list slicing. The syntax is basically my_list[start_index:end_index]

>>> i = [0,1,2,3,4,5]
>>> i[:3] # same as i[0:3] - grabs from first to third index (0->2)
[0, 1, 2]
>>> i[3:] # same as i[3:len(i)] - grabs from fourth index to end
[3, 4, 5]

To get the first half of the list, you slice from the first index to len(i)//2 (where // is the integer division - so 3//2 will give the floored result of1, instead of the invalid list index of1.5`):

>>> i[:len(i)//2]
[0, 1, 2]

..and the swap the values around to get the second half:

>>> i[len(i)//2:]
[3, 4, 5]

While the answers above are more or less correct, you may run into trouble if the size of your array isn't divisible by 2, as the result of a / 2, a being odd, is a float in python 3.0, and in earlier version if you specify from __future__ import division at the beginning of your script. You are in any case better off going for integer division, i.e. a // 2, in order to get "forward" compatibility of your code.


If you have a big list, It's better to use itertools and write a function to yield each part as needed:

from itertools import islice

def make_chunks(data, SIZE):
    it = iter(data)
    # use `xragne` if you are in python 2.7:
    for i in range(0, len(data), SIZE):
        yield [k for k in islice(it, SIZE)]

You can use this like:

A = [0, 1, 2, 3, 4, 5, 6]

size = len(A) // 2

for sample in make_chunks(A, size):
    print(sample)

The output is:

[0, 1, 2]
[3, 4, 5]
[6]

Thanks to @thefourtheye and @Bede Constantinides


10 years later.. I thought - why not add another:

arr = 'Some random string' * 10; n = 4
print([arr[e:e+n] for e in range(0,len(arr),n)])

With hints from @ChristopheD

def line_split(N, K=1):
    length = len(N)
    return [N[i*length/K:(i+1)*length/K] for i in range(K)]

A = [0,1,2,3,4,5,6,7,8,9]
print line_split(A,1)
print line_split(A,2)

This is similar to other solutions, but a little faster.

# Usage: split_half([1,2,3,4,5]) Result: ([1, 2], [3, 4, 5])

def split_half(a):
    half = len(a) >> 1
    return a[:half], a[half:]

#for python 3
    A = [0,1,2,3,4,5]
    l = len(A)/2
    B = A[:int(l)]
    C = A[int(l):]       

참고URL : https://stackoverflow.com/questions/752308/split-list-into-smaller-lists-split-in-half

반응형