-1

So I want to know the position of the randomly named_tuples sampled by the random.choices.

I sample it with a list of the same length and positions (memory, probabilities)

sample_indices = random.choices(self.memory, k=batch_size, weights=sample_probs)
Type of memory : <class 'list'>
Type of memory index 0 : <class 'memory.Transion'>
Type of sample_indices : <class 'list'>
Type of sample_indices index  0 : <class 'memory.Transion'>

However, if I try to use the usual way (self.memory[sample_indices]) of finding its index I get this error :

TypeError: list indices must be integers or slices, not list

Is anyone familiar with similar features which allow for finding the index or?

Thanks

Prajwal Kulkarni
  • 1,480
  • 13
  • 22
  • The error and output very clearly shows that ``self.memory`` and ``sample_indices`` are both lists, so ``self.memory[sample_indices]`` doesn't make much sense. Notably, it *isn't* "the usual way of finding its index" – that would be ``self.memory.index(sample_indices)``. Can you [edit] the question to provide a [mre], most importantly clarifying the expected output? – MisterMiyagi Nov 12 '21 at 12:48

1 Answers1

1

If I understand your question correctly, you want to make a random selection from a sequence and get both the elements themselves and their indices in the original sequence.

One way to do this without looking up the index of each element after the fact is to run random.choices on an enumerated list:

import random

memory = ["a", "b", "c", "d", "e"]

selection = random.choices(list(enumerate(memory)), k=3)

for index, element in selection:
    print(f"index: {index}, element: {element}")

Example output:

index: 2, element: c
index: 4, element: e
index: 0, element: a

Note that this will make a copy of the original list, so may be unsuitable depending on size.

Phydeaux
  • 2,795
  • 3
  • 17
  • 35