how to get the index of numpy.random.choice? - python

前端 未结 8 1405
粉色の甜心
粉色の甜心 2021-02-02 12:31

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 ran

8条回答
  •  面向向阳花
    2021-02-02 12:47

    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
    

提交回复
热议问题