Home > database >  I made an code with command append, to compare two tensors with pytorch. What's wrong with it?
I made an code with command append, to compare two tensors with pytorch. What's wrong with it?

Time:11-29

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()

What I expected was: [0,3].

But the result was : [0]. I don't get what's wrong with it. Did I use append wrongly?

CodePudding user response:

Your return statement is inside for and if. Pull it outside at the level of function definition

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

Earlier, your function was returning just after encountering 0. That's why 3 was missing.

  • Related