파일에 쓰려면 목록에서 임의로 50 개의 항목을 선택하십시오.


129

지금까지 파일을 가져오고 새 파일을 만들고 목록을 무작위 화하는 방법을 알아 냈습니다.

파일에서 쓸 항목을 무작위로 목록에서 50 개만 선택하는 데 문제가 있습니까?

def randomizer(input,output1='random_1.txt',output2='random_2.txt',output3='random_3.txt',output4='random_total.txt'):

#Input file 
    query=open(input,'r').read().split()
    dir,file=os.path.split(input)

    temp1 = os.path.join(dir,output1)
    temp2 = os.path.join(dir,output2)
    temp3 = os.path.join(dir,output3)
    temp4 = os.path.join(dir,output4)


    out_file4=open(temp4,'w')

    random.shuffle(query)

    for item in query:
        out_file4.write(item+'\n')   

총 랜덤 화 파일이

example:

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

첫 번째 임의의 세트 3, 두 번째 임의의 세트 3 및 세 번째 임의의 세트 3을 가진 3 개의 파일 (out_file1 | 2 | 3)을 원합니다 (이 예제의 경우 만들려는 파일은 50이어야 함)

random_1 = ['9','2','3']
random_2 = ['1','5','6']
random_3 = ['8','7','0']

따라서 마지막 '4'는 포함되지 않습니다.

무작위로 지정한 목록에서 50을 어떻게 선택할 수 있습니까?

더 좋은 방법은 원래 목록에서 무작위로 50을 어떻게 선택할 수 있습니까?


무슨 소리 야?
O.rka

답변:


269

목록이 무작위 순서이면 처음 50 개만 가져갈 수 있습니다.

그렇지 않으면

import random
random.sample(the_list, 50)

random.sample 도움말 텍스트 :

sample(self, population, k) method of random.Random instance
    Chooses k unique random elements from a population sequence.

    Returns a new list containing elements from the population while
    leaving the original population unchanged.  The resulting list is
    in selection order so that all sub-slices will also be valid random
    samples.  This allows raffle winners (the sample) to be partitioned
    into grand prize and second place winners (the subslices).

    Members of the population need not be hashable or unique.  If the
    population contains repeats, then each occurrence is a possible
    selection in the sample.

    To choose a sample in a range of integers, use xrange as an argument.
    This is especially fast and space efficient for sampling from a
    large population:   sample(xrange(10000000), 60)

1
random.sample선택한 지수도 반환 할 수 있습니까 ?
zyy

43

임의의 항목을 선택하는 쉬운 방법 중 하나는 셔플 한 다음 슬라이스하는 것입니다.

import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables

@MonicaHeddneck 왜 무작위 셔플 링과 슬라이싱이 더 좋을까요? 선택을 무작위 화하여 많은 수의 샘플을 선택하지 않으면 무작위 셔플 링과 동일한 장점을 가지며 섞은 샘플 조각을 가져 가지 않습니까? 설명해 주시겠습니까? 감사.
salvu

7
이것을 사용하여 기계 학습 프로젝트를위한 테스트 / 트레인 세트를 쉽게 만들었습니다. 이렇게하면 random.choice(mylist,3)두 개의 분리 세트가 생성되지 않습니다.
Monica Heddneck

29

random.choice()더 나은 옵션 이라고 생각 합니다.

import numpy as np

mylist = [13,23,14,52,6,23]

np.random.choice(mylist, 3, replace=False)

이 함수는 목록에서 무작위로 선택된 3 개의 값으로 구성된 배열을 반환합니다.


7
나는 당신이 사용해야한다고 생각합니다 random.choice(mylist, 3, replace=False). 또한 덜 사용하는 혼란 import numpy as npnp.random.choice(mylist, 3, replace=False)
존 라 Rooy

10
이것은 목록 항목을 반복 할 가능성이 있습니다
Paullo

더 좋은 옵션은 아닙니다. ~ 100 배 느립니다
nitesh kansal

-3

목록에 100 개의 요소가 있고 임의의 방법으로 50 개를 선택한다고 가정하십시오. 수행 할 단계는 다음과 같습니다.

  1. 라이브러리 가져 오기
  2. 난수 생성기의 시드를 생성합니다.
  3. 무작위로 수령 할 수있는 번호 목록을 준비하십시오.
  4. 숫자 목록에서 무작위로 선택하십시오

암호:

from random import seed
from random import choice

seed(2)
numbers = [i for i in range(100)]

print(numbers)

for _ in range(50):
    selection = choice(numbers)
    print(selection)
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.