【问题标题】:Random division of list to two complementary sublists将列表随机划分为两个互补的子列表
【发布时间】:2014-08-21 05:03:04
【问题描述】:

我有一个列表,我想将它随机分成两个已知大小的子列表,它们是相互补充的。例如,我有[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],我的代码目前无法提供。

是否有一些我错过的随机内置选项?谁能提供一个简单的解决方案?

【问题讨论】:

  • 所以物品的顺序也很重要?
  • 我在问题中写道 - 它没有。

标签: python list python-2.7 random


【解决方案1】:

这样的事情怎么样?

生成索引列表并打乱它们:

>>> 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)

【讨论】:

  • 在 Python 3 中,range 返回一个惰性序列对象。在获取项目之前,您必须将对象转换为列表:indices = list(range(len(pop)))
猜你喜欢
  • 1970-01-01
  • 2020-02-07
  • 2011-03-22
  • 2016-07-30
  • 2010-09-27
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
  • 2021-01-07
相关资源
最近更新 更多