[英]Limit on the number of values returned by a Python function/method
I was working with some code and realised that things became a lot easier when a single method was returning 4 values. 我正在使用一些代码,并意识到当单个方法返回4个值时,事情变得容易多了。 Working with traditional languages like C++ and Java where methods return only a single value, I came to wonder
使用传统语言,如C ++和Java,其中方法只返回一个值,我开始怀疑
Is there a limit on the number of values returned by a Python function?
Python函数返回的值的数量是否有限制?
Stuff like this works effortlessly. 像这样的东西毫不费力地工作。 Is there a limit to it?
它有限制吗?
def hello():
return 1, 2, 3, 4, 5
a, b, c, d, e = hello()
print a, b, c, d, e
Stragely enough, I didn't find any answer to this question 令人沮丧的是,我没有找到任何答案
If you return multiple values, you actually return a tuple . 如果返回多个值,则实际返回一个元组 。 Indeed:
确实:
return 1,4,2,5
is short for: 是短的:
return (1,4,2,5)
So the question boils down to how many items a tuple can carry . 所以问题归结为一个元组可以携带多少项 。 The answer can be obtained with:
答案可以通过以下方式获得:
import sys
sys.maxsize
It is usually 2 31 -1=2 147 483 647 on a 32-bit system and 2 63 -1=9 223 372 036 854 775 807 on a 64-bit system. 在32位系统上通常为2 31 -1 = 2 147 483 647,在64位系统上为2 63 -1 = 9 223 372 036 854 775 807。 The strange thing is: it is not 2 32 -1 (or 2 64 -1) so that means that technically speaking if you have a 32-bit machine, and your have 4 GiB in place, the list itself can only fill up half of the memory (of course the elements in the list can be responsible to fill up the remaining half).
奇怪的是:它不是2 32 -1(或2 64 -1)所以这意味着从技术上讲,如果你有一台32位机器,并且你有4 GiB,列表本身只能填满一半记忆(当然列表中的元素可以负责填补剩余的一半)。
Of course the elements also need to fit into memory: if you have no space left to store five million elements, your program will crash anyway. 当然元素也需要适合内存:如果你没有空间来存储500万个元素,你的程序无论如何都会崩溃。
Python functions only return a single value: a reference to an object. Python函数只返回一个值:对象的引用。 That object may be of any type, including a tuple (which is what's constructed with
return 1, 2, 3, 4, 5
). 该对象可以是任何类型,包括元组(这是由
return 1, 2, 3, 4, 5
构造的)。 The size of the object is only limited by your computer's available memory. 对象的大小仅受计算机可用内存的限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.