将列表随机划分为两个互补的子列表(Random division of list to two complementary sublists)

我有一个列表,我想随机分成两个已知大小的子列表,它们是彼此的补充。 例如,我有[1,5,6,8,9] ,我想把它分为[1,5,9]和[6,8] 。 我不太关心效率,只是想让它发挥作用。 订单无关紧要。

我开始时:

pop = [...] #some input samp1 = random.sample(pop, samp1len) samp2 = [x for x in pop if x not in samp1]

但是,此解决方案因重复项而失败。 如果pop = [0,0,0,3,5] ,并且长度3的第一个选择是[0,3,5] ,我仍然希望samp2为[0,0] ,我的代码目前无法提供。

我错过了一些随机的内置选项吗? 有人能提供简单的解决方案吗?

I have a list which I want to randomly divide into two sublists of known size, which are complements of one another. e.g., I have [1,5,6,8,9] and I want to divide it to [1,5,9] and [6,8]. I care less about efficiency and just want it to work. Order does not matter.

I started with:

pop = [...] #some input samp1 = random.sample(pop, samp1len) samp2 = [x for x in pop if x not in samp1]

However, this solution fails with repetitive items. If pop = [0,0,0,3,5], and the first selection of length 3 was [0,3,5], I would still like samp2 to be [0,0], which my code currently fails to provide.

Is there some built in option in random that I missed? Can anyone offer a simple solution?

最满意答案

这样的事怎么样?

生成索引列表并对其进行随机播放:

>>> indices = range(len(pop)) >>> random.shuffle(indices)

然后切片索引列表并使用operator.itemegetter获取项目:

>>> from operator import itemgetter >>> itemgetter(*indices[:3])(pop) (0, 0, 3) >>> itemgetter(*indices[3:])(pop) (5, 0)

How about something like this?

Generate a list of indices and shuffle them:

>>> indices = range(len(pop)) >>> random.shuffle(indices)

Then slice the indices list and use operator.itemegetter to get the items:

>>> from operator import itemgetter >>> itemgetter(*indices[:3])(pop) (0, 0, 3) >>> itemgetter(*indices[3:])(pop) (5, 0)

更多推荐