列表中的互斥随机抽样
问题内容:
input = ['beleriand','mordor','hithlum','eol','morgoth','melian','thingol']
我在不重复任何元素的情况下无法创建X个大小为Y的列表。
我一直在使用:
x = 3
y = 2
import random
output = random.sample(input, y)
# ['mordor', 'thingol']
但是如果我重复一次,那么我会重复。
我希望输出是这样的
[['mordor', 'thingol'], ['melian', 'hithlum'], ['beleriand', 'eol']]
因为我选择了x = 3
(3个列表)大小y = 2
(每个列表2个元素)。
def random_generator(x,y):
....
问题答案:
而不是从列表中随机获取两件事,只需随机化列表并对其进行遍历即可创建您指定尺寸的新数组!
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)