주어진 목록에서 대체하지 않고 파이썬 반복 샘플링 [중복]

Nov 18 2020

(예) 정수 목록이 주어지면 n대체하지 않고 요소를 샘플링하고 원래 목록에서 샘플링 된 항목을 제거하고 원래 목록의 요소가 남아있을 때까지이 프로세스를 반복하고 싶습니다 . 의 목록을 반환합니다 round(len(list)/n).

에 대해 알고 random.sample()있지만 교체하지 않고 반복 샘플링에 대한 구현을 찾지 못했습니다. 아래의 의사 코드에는 원본 목록에서 샘플링 된 요소가 제거되지 않았습니다. 그러나이 함수를 작성하는 동안 이미 구현 된 것과 같은 것이 없거나 이에 대한 더 우아한 솔루션이 없는지 궁금합니다.

의사 코드

def repeated_sample_without_replacement(my_list, n):
    # where n = number of samples,
    k = int(len(my_list) / n)
    if len(my_list)%n != 0:
        samples = np.repeat(n,k)
        samples = np.append(samples, len(my_list) % n)
    else:
        samples = np.repeat(n,k)
    k = len(my_list) / n
    out = []
    for s in samples:
        out.append(random.sample(my_list, s))
        # remove the now sample elements from my_list
    
    return out

x = repeated_sample_without_replacement(ids,10)
print(x)

예제 데이터

# Sample Data
ids_clean = [*range(1,40)]
In[71]: # Remove Some ID to Better Represent my Purpose
ids = ids_clean[:12] + ids_clean[13:26] + ids_clean[27:]
ids
Out[73]: 
[1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 11,
 12,
 14,
 15,
 16,
 17,
 18,
 19,
 20,
 21,
 22,
 23,
 24,
 25,
 26,
 28,
 29,
 30,
 31,
 32,
 33,
 34,
 35,
 36,
 37,
 38,
 39]
len(ids)
Out[74]: 37

원하는 출력

[[1,4,5,6..],[2,8,9,...],[13,15,16,...][27,10,..]]

답변

4 superbrain Nov 18 2020 at 00:30

코드는 주어진 전체 목록을 전체적으로 샘플링하려고한다는 것을 보여줍니다. 그래서 random.shuffle한 번만 그런 다음 청크로 분할하십시오. 또는 step으로 슬라이스 만하면 n더 쉽게 만들 수 있습니다.

from random import shuffle

def repeated_sample_without_replacement(my_list, n):
    shuffle(my_list)
    return [my_list[i::n] for i in range(n)]

데모:

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

이것은 실제로 정확히 n샘플을 생성합니다 . 당신과 다소 비슷하지 않습니다.

당신의 데모 :

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