如何获取numpy.random.choice的索引? - Python [英] how to get the index of numpy.random.choice? - python
问题描述
是否可以修改numpy.random.choice函数以使其返回所选元素的索引? 基本上,我想创建一个列表并随机选择元素而无需替换
Is it possible to modify the numpy.random.choice function in order to make it return the index of the chosen element? Basically, I want to create a list and select elements randomly without replacement
import numpy as np
>>> a = [1,4,1,3,3,2,1,4]
>>> np.random.choice(a)
>>> 4
>>> a
>>> [1,4,1,3,3,2,1,4]
a.remove(np.random.choice(a))
将删除列表中遇到的那个值的第一个元素(在上面的示例中为a[1]
),该元素可能不是所选元素(例如,a[7]
).
a.remove(np.random.choice(a))
will remove the first element of the list with that value it encounters (a[1]
in the example above), which may not be the chosen element (eg, a[7]
).
推荐答案
这是找出随机选择的元素的 index 的一种方法:
Here's one way to find out the index of a randomly selected element:
import random # plain random module, not numpy's
random.choice(list(enumerate(a)))[0]
=> 4 # just an example, index is 4
或者您也可以在一个步骤中检索元素和:
Or you could retrieve the element and the index in a single step:
random.choice(list(enumerate(a)))
=> (1, 4) # just an example, index is 1 and element is 4
这篇关于如何获取numpy.random.choice的索引? - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!