列表中的互斥随机抽样 [英] Mutually exclusive random sampling from a list

查看:113
本文介绍了列表中的互斥随机抽样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

input = ['beleriand','mordor','hithlum','eol','morgoth','melian','thingol']

在不重复任何元素的情况下,我无法创建X个大小为Y的列表.

I'm having trouble creating X number of lists of size Y without repeating any elements.

我一直在使用:

x = 3
y = 2

import random

output = random.sample(input, y)
# ['mordor', 'thingol']

但是如果我重复一次,那么我会重复.

but if I repeat this then I will have repeats.

我希望输出是类似的

[['mordor', 'thingol'], ['melian', 'hithlum'], ['beleriand', 'eol']]

因为我选择了大小为y = 2(每个列表2个元素)的x = 3(3个列表).

since I chose x = 3 (3 lists) of size y = 2 (2 elements per list).

def random_generator(x,y):
    ....

推荐答案

与其从列表中随机抽取两件事,不如对列表进行随机化并对其进行遍历,以创建您指定尺寸的新数组!

rather than randomly taking two things from your list, just randomize your list and iterate through it to create your new array of the dimensions you specify!

import random
my_input = ['beleriand','mordor','hithlum','eol','morgoth','melian','thingol']
def random_generator(array,x,y):
    random.shuffle(array)
    result = []
    count = 0
    while count < x:
        section = []
        y1 = y * count
        y2 = y * (count + 1)
        for i in range (y1,y2):
            section.append(array[i])
        result.append(section)
        count += 1
    return result
print random_generator(my_input,3,2)

这篇关于列表中的互斥随机抽样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆