リストからランダムに50項目を選択する 質問する

リストからランダムに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 個を選択するにはどうすればよいでしょうか?

ベストアンサー1

リストがランダムな順序になっている場合は、最初の 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)

おすすめ記事