반응형
목록에서 무작위로 50개 항목 선택
파일의 아이템 리스트를 읽어내는 기능이 있습니다.목록에서 50개 항목만 무작위로 선택하여 다른 파일에 쓰려면 어떻게 해야 하나요?
def randomizer(input, output='random.txt'):
query = open(input).read().split()
out_file = open(output, 'w')
random.shuffle(query)
for item in query:
out_file.write(item + '\n')
예를 들어, 총 랜덤화 파일이
random_total = ['9', '2', '3', '1', '5', '6', '8', '7', '0', '4']
랜덤으로 3개씩 세팅하고 싶은데 결과는
random = ['9', '2', '3']
무작위로 추출한 목록에서 50을 선택하려면 어떻게 해야 합니까?
게다가 어떻게 하면 원래 리스트에서 무작위로 50개를 선택할 수 있을까요?
목록이 무작위로 나열되어 있으면 처음 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)
임의의 아이템을 쉽게 선택할 수 있는 방법은 셔플 후 슬라이스하는 것입니다.
import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables
생각합니다random.choice()더 나은 선택입니다.
import numpy as np
mylist = [13,23,14,52,6,23]
np.random.choice(mylist, 3, replace=False)
함수는 목록에서 무작위로 선택된 3개의 값의 배열을 반환합니다.
샘플은 3개 있습니다('사과', '사과').시리즈 작성. 7개의 요소를 포함하고 목록에서 무작위로 선택되어야 합니다.
random.choice
import random import numpy as np fruits = ['orange','mango','apple'] np.random.choice(fruits, 7, replace=True)산출량
array(['orange', 'mango', 'apple', 'orange', 'orange', 'mango', 'apple'], dtype='<U6')리스트에서 랜덤 선택(3개 미만의 값)
random.sample
import random random.sample(fruits, 3)
목록에 100개의 요소가 있고 그 중 50개를 무작위로 선택하려고 합니다.다음 단계를 수행합니다.
- 라이브러리 Import
- 난수 생성기의 시드를 만듭니다. 나는 그것을 2에 두었습니다.
- 무작위로 픽업할 번호 목록을 준비합니다.
- 숫자 목록에서 임의로 선택
코드:
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)
언급URL : https://stackoverflow.com/questions/15511349/select-50-items-from-list-at-random
반응형
'source' 카테고리의 다른 글
| Realm Swift: 결과를 Swift Array로 변환 (0) | 2023.04.12 |
|---|---|
| 클릭 후 WPF 버튼이 강조 표시된 상태로 유지되지 않도록 하려면 어떻게 해야 합니까? (0) | 2023.04.12 |
| SQL Server - 트랜잭션 롤백 오류 발생? (0) | 2023.04.07 |
| SQL Server의 숨겨진 기능 (0) | 2023.04.07 |
| SQL Server 출력 절을 스칼라 변수로 변환 (0) | 2023.04.07 |