我用命令追加编写了一个代码,用 pytorch 比较两个张量。它出什么问题了?
I made an code with command append, to compare two tensors with pytorch. What's wrong with it?
xxx=torch.tensor([True,True,False,True])
xxxz=torch.tensor([True,False,False,True])
def zzz():
asdf=[]
for i in range(4):
if xxx[i] == xxxz[i] and xxx[i] == True:
asdf.append(i)
return asdf
zzz()
我的预期是:[0,3]。
但结果是:[0]。我不明白这有什么问题。我是不是用错了append?
您的 return 语句在 for
和 if
中。在函数定义级别将其拉到外面
def zzz():
asdf=[]
for i in range(4):
if xxx[i] == xxxz[i] and xxx[i] == True:
asdf.append(i)
# return asdf # NOPE
return asdf # THIS
早些时候,您的函数在遇到 0 之后 returning。这就是缺少 3 的原因。
xxx=torch.tensor([True,True,False,True])
xxxz=torch.tensor([True,False,False,True])
def zzz():
asdf=[]
for i in range(4):
if xxx[i] == xxxz[i] and xxx[i] == True:
asdf.append(i)
return asdf
zzz()
我的预期是:[0,3]。
但结果是:[0]。我不明白这有什么问题。我是不是用错了append?
您的 return 语句在 for
和 if
中。在函数定义级别将其拉到外面
def zzz():
asdf=[]
for i in range(4):
if xxx[i] == xxxz[i] and xxx[i] == True:
asdf.append(i)
# return asdf # NOPE
return asdf # THIS
早些时候,您的函数在遇到 0 之后 returning。这就是缺少 3 的原因。