简体   繁体   English

如何从python中的函数返回字典和多个变量?

[英]How to return a dictionary and multiple variables from a function in python?

I am trying to set up a function that records to 2 variables and a dictionary, the dictionar works but the two variables return the wrong things 我试图建立一个记录两个变量和一个字典的函数,字典工作,但是两个变量返回错误的内容

mydict{}
fname = 0
lname = 0

def enterdetails(fname, lname):
    fname = input ("First Name: ");
    fnamedict = fname
    mydict['FirstName'] = fnamedict;

   lname = input ("Last Name: ");
   lnamedict = lname
   mydict['LastName'] = lnamedict;
   print(fname)
   print(lname)

   return mydict
   return (fname, lname)

fname, lname = enterdetails(fname, lname)
print(fname, lname)
print(mydict)

However the variables of fname and lname come out as FirstName and LastName respectively. 但是,fname和lname的变量分别作为FirstName和LastName出现。 How would I fix this? 我该如何解决?

You have two return statements, but only the first is returned. 您有两个return语句,但是只返回第一个。 Instead, return all three variables together as a tuple: 相反,将所有三个变量作为元组一起返回:

def enterdetails(fname, lname):
    ...
    return mydict, fname, lname

mydict, fname, lname = enterdetails(fname, lname)
print(fname, lname)
print(mydict)

The dictionary works because you have it set as a global variable . 该词典之所以有效,是因为您已将其设置为global variable However, the function is actually returning the "dictionary" first, so your unpacking is all messed up. 但是,该函数实际上首先返回了“字典”,因此您的解压过程一团糟。

Remove the return mydict or use return mydict, (fname, lname) , so you will end up with: 删除return mydict或使用return mydict, (fname, lname) ,因此您将得到以下结果:

mydict, (fname, lname) = enterdetails(fname, lname)

But as I mentioned above, mydict is a global variable, so it is unnecessary to return the value. 但是如上所述, mydict是一个全局变量,因此没有必要返回该值。

You can't put a return under a return like 你不能把一个return一个下return

return mydict
return (fname, lname) #this won't return any thing

One of the ways that you could do is: 您可以采取的方法之一是:

  ....
  return [mydict, fname, lname]

data = enterdetails(fname, lname)
mydict = data[0]
fname = data[1]
lname = data[2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM