当前位置: 首页 > 面试题库 >

从列表中随机选择50个项目写入文件

袁翰池
2023-03-14
问题内容

到目前为止,我已经弄清楚了如何导入文件,创建新文件以及使列表随机化。

我在从列表中随机选择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个文件(out_file1 | 2 | 3),其中第一个随机集为3,第二个随机集为3,第三个随机集为3(在此示例中,但我要创建的文件应该有50个)

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

因此,不会包含最后一个“ 4”,这很好。

如何从随机选择的列表中选择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)


 类似资料:
  • 问题内容: 如何从Java列表中随机选择一个项目?例如我有 等等…。如何使用 问题答案: 像这样吗

  • 问题内容: 假设我有以下列表: 从此列表中随机检索项目的最简单方法是什么? 问题答案: 采用 对于加密安全的随机选择(例如,用于从单词列表生成密码短语),请使用 secrets是Python 3.6中的新功能,在旧版本的Python上,你可以使用此类:

  • 问题内容: 我正在尝试建立一个用户可以提交照片的网站,然后在另一个页面上一个一个地随机查看其他照片。我有一个名为“上传”的目录,其中提交了图片。我无法从文件中读取图片。我只想从目录上传中随机选择一张图片,并将其显示在页面上。任何建议表示赞赏。 问题答案: 您可以使用glob获取目录中的所有文件,然后从该数组中获取随机元素。这样的函数将为您完成此任务:

  • 我试图在Python中创建一个随机列表。每次运行代码时,列表中的随机单词都会按顺序出现。我想做的是: 目标是要求用户从将要显示的列表中选择一些内容。下面是我想要的输出示例:

  • 问题内容: 我正在使用PHP和MySQL创建一个简单的Web应用程序。在其中,我需要以随机顺序从表中随机选择一小组行。如何使用MySQL实现此类目标? 问题答案: SELECT * FROM table ORDER BY RAND() LIMIT 10;