Python随机选择具有命名元组的索引



所以我想知道random.choices采样的随机命名元组的位置。

我用相同长度和位置(记忆、概率(的列表对其进行采样

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

然而,如果我尝试使用通常的方法(self.memory[sample_indices](来查找其索引,我会得到以下错误:

TypeError:列表索引必须是整数或切片,而不是列表

有人熟悉允许查找索引或的类似功能吗?

感谢

如果我正确理解你的问题,你想从序列中进行随机选择,并在原始序列中获得元素本身和它们的索引。

一种不需要在事后查找每个元素的索引的方法是在enumerated列表上运行random.choices

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

示例输出:

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

请注意,这将复制原始列表,因此根据大小可能不合适。

相关内容

最新更新