我正在制作一个随机化器来输入名称,然后将它们按2个偶数组打印出来。我正在尝试弄清楚如何将列表分成几组。
答案 0 :(得分:0)
如果我做对了,您可以使用numpy
和random.sample
:
import numpy as np
import random
# here goes your list
your_list = np.array(["name1", "name2","name3", "name4","name5", "name6","name7", "name8"])
# get its length
n_names = len(your_list)
# generates a random list od indexes
groups = random.sample(range(n_names), n_names)
# split these indixes into two even groups
g1, g2 = groups[:n_names//2], groups[n_names//2:]
# put elements into two groups
group1, group2 = your_list[g1], your_list[g2]
# print them
print("Group1: ",group1)
print("Group2: ",group2)
如果没有问题,您可以尝试以下简单的解决方案:
import random
# here goes your list
your_list = np.array(["name1", "name2","name3", "name4","name5", "name6","name7", "name8"])
# get its length
n_names = len(your_list)
# shuffle it
random.shuffle(your_list)
group1, group2 = your_list[:n_names//2], your_list[n_names//2:]
# print them
print("Group1: ",group1)
print("Group2: ",group2)