我有 3 个数组,a1、a2、a3
我想一次把他们三个都还回去。
我有
return a1, a2, a3
但它将它们全部返回到同一行,我想知道如何将它们分别返回到新行
你的意思是这样吗?
>>> def f():
... a1 = [1, 2, 3]
... a2 = [4, 5, 6]
... a3 = [7, 8, 9]
... return a1, a2, a3
...
>>> f()
([1, 2, 3], [4, 5, 6], [7, 8, 9])
您可以像这样解压返回值
>>> b1, b2, b3 = f()
>>> b1
[1, 2, 3]
>>> b2
[4, 5, 6]
>>> b3
[7, 8, 9]
或者像这样打印在 3 行上
>>> print "\n".join(str(x) for x in f())
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
你是否要求能够做到
return a1
return a2
return a3
代替
return a1, a2, a3
???
如果是这样,我很抱歉,但你不能那样做。当您使用时,return a1, a2, a3
您实际上是在返回一件事,即 3 个列表的元组。执行 return 语句将返回当前范围/上下文之外的调用者。如果这不是您想要做的,请更清楚地解释您的目标。
一个方法只能返回一次。但是,仍然可以在不同的行上访问数据。
def dosomething():
...
return a1, a2, a3
myTuple = dosomething()
first = myTuple[0]
second = myTuple[1]
third = myTuple [2]
I think you're treating an array like a string - arrays don't span "lines" per say.
Maybe this is what you're looking for; if I understood correctly.
return str(a1)+'\n'+str(a2)+'\n'+str(a3)
如果 a1、a2、a3 的长度相同,你可以试试这个
a1 = [1, 2, 3]
a2 = [4, 5, 6]
a3 = [7, 8, 9]
[ (a1[x],a2[x],a3[x]) for x in range(len(a1)) ]
>>> [(1, 4, 7), (2, 5, 8), (3, 6, 9)]