带有异常的Python随机样本 [英] Python random sample with exception
问题描述
我正在尝试创建myList
的示例,但i_
除外.
I'm attempting to create a sample of myList
with the exception of i_
.
我的尝试:
i_ = 'd'
myList = ['a','b','c','d','e']
myList = random.sample(myList, 3)
尽管上面的示例工作正常,但仍有可能从myList
中删除i_
.
Although the above sample works fine, there is still a chance that i_
is removed from myList
.
我想创建一个样本,而不会删除i_
的值.
I would like to create a sample without the value of i_
being removed.
所需的输出:
Desired Output:
任何包含3个项目的列表输出,包括i_
,例如:
Any list output containing 3 items including i_
, e.g:
['a','d','e']
推荐答案
仅从列表中抽取2个值,而不使用i_
并在以后插入i_
:
Just sample 2 values from the list without the i_
and insert i_
later:
new_list = random.sample([i for i in myList if i != i_], 2)
new_list.insert(random.randrange(0, 3), i_)
但是,这假设i_
在您的列表中仅出现一次-在您的示例中似乎是合理的,但出于完整性考虑,我想提及这一点.另外,如果列表中有多个i_
,我也不确定期望的结果是什么.
But this assumes that i_
occurs only once in your list - seems reasonable given your example but I wanted to mention this for completeness. Also I'm not sure what the desired result should be if there were multiple i_
in the list.
您还可以使用hit& miss方法来生成示例,直到获得包含i_
的示例:
You could also use a hit&miss approach that generates a sample until you get one that contains i_
:
new_list = []
while i_ not in new_list:
new_list = random.sample(myList, 3)
请注意,如果不太可能在示例中绘制i_
,则这可能会非常慢.对于5个元素的3个样本,它相当快,但是如果从1000个元素中绘制3个样本,则它可能会真的很慢.
Note that this could be really slow if it's unlikely that i_
is drawn in the sample. For a 3-sample of 5 elements it's quite fast but it could be really slow if you draw a 3-sample from 1000 elements.
这篇关于带有异常的Python随机样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!