python - 如何检查 NamedTuple 是否在列表中?
问题描述
我试图检查 NamedTuple “Transition” 的 inctance 是否等于列表“self.memory”中的任何对象。
这是我尝试运行的代码:
from typing import NamedTuple
import random
import torch as t
Transition = NamedTuple('Transition', state=t.Tensor, action=int, reward=int, next_state=t.Tensor, done=int, hidden=t.Tensor)
class ReplayMemory:
def __init__(self, capacity):
self.memory = []
self.capacity = capacity
self.position = 0
def store(self, *args):
print(self.memory == Transition(*args))
if Transition(*args) in self.memory:
return
if len(self.memory) < self.capacity:
self.memory.append(None)
self.memory[self.position] = Transition(*args)
...
这是输出:
False
False
我得到的错误是:
...
if Transition(*args) in self.memory:
RuntimeError: bool value of Tensor with more than one value is ambiguous
这对我来说似乎很奇怪,因为打印告诉我“==”操作返回一个布尔值。
如何正确地做到这一点?
谢谢
编辑:
*args 是一个元组,由
torch.Size([16, 12])
int
int
torch.Size([16, 12])
int
torch.Size([4])
解决方案
我相信你应该明确定义平等。
from typing import NamedTuple
import random
import torch as t
class Sample(NamedTuple):
state: t.Tensor
action: int
def __eq__(self, other):
return bool(t.all(self.state == other.state)) and self.action == other.action
推荐阅读
- python - 请求获取数据从 pc 发送到 django 应用程序的请求中没有产生任何结果
- javascript - 如何使用字符串和数组创建对象数组
- javascript - 单击链接不会将我带到锚标记内的 href 链接
- scheme - 我可以使用附加!在文字列表上?
- python - AttributeError: 'str' 对象在噪声 = np.random.normal(0, 20, file_name.shape) 处没有属性 'shape'
- javascript - Javascript Excel Javascript API 脚本实验室中使用的 Danfo.js 库
- typescript - vuejs - v-model 不更新类属性
- javascript - 如何在 react native 中设置 redux?
- r - 用 0 按组替换前导 NA,但保留其他 NA
- java - 你好!将 ImageIcon 设置为 Jframe 和其他组件似乎不起作用。我需要帮助