[英]Python random.choices index with named tuples
所以我想知道random.choices采樣的隨機named_tuples的位置。
我用相同長度和位置的列表(內存、概率)對其進行采樣
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: list indices must be integers or slices, not list
有沒有人熟悉允許查找索引的類似功能?
謝謝
如果我正確理解您的問題,您希望從序列中隨機選擇並獲取原始序列中的元素本身及其索引。
一種在事后不查找每個元素的索引的情況下執行此操作的方法是在enumerate
d 列表上運行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
請注意,這將復制原始列表,因此根據大小可能不合適。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.