Possible Duplicate:
Why do we need tuples in Python (or any immutable data type)?可能的重复:为什么我们需要Python中的元组(或任何不可变的数据类型)?
I'm learning Python and have background in Ruby. Not ever having tuples, I can't imagine why I would need them or why Python leans on them so much.
我正在学习Python,并有Ruby背景。从来没有过元组,我无法想象为什么我需要它们,或者为什么Python会如此依赖它们。
3 个解决方案
#1
4
The coordinates of a square on a chessboard is one example of good use of tuple. I usually use a Python dict, indexed by tuple, to implement a multidimensional array, rather than list-of-lists or the numpy or array modules:
棋盘上正方形的坐标是使用元组的一个很好的例子。我通常使用Python dict(按tuple索引)实现多维数组,而不是列表列表或numpy或数组模块:
board = {}
board[ 3, 6 ] = "black queen"
board[ 0, 0 ] = "white king"
You can't use a mutable (like a list) as a dictionary key, so you need a tuple for this.
不能使用可变的(如列表)作为字典键,因此需要为此使用一个tuple。
Occasionally you find yourself wanting to return multiple values from a function - a boolean to indicate success or failure plus a string describing the failure mode, for instance:
有时你会发现自己想要从一个函数返回多个值——一个布尔值表示成功或失败,加上一个描述失败模式的字符串,例如:
if trickyOperationSucceeds():
return True,"Success!"
return False,"The tricky thing failed!"
This isn't a pattern to use a lot, but sometimes it gets you out of trouble. You could also use a list here; it's only by convention that you'd normally use tuple instead.
这不是一个经常使用的模式,但有时它会让你摆脱麻烦。你也可以在这里使用一个列表;只有按照惯例,你通常才会使用tuple。
When considering how to represent independent values that have to be passed around together, there's almost a continuum between tuples, dicts, and classes. Consider three ways of representing that compound return:
当考虑如何表示必须一起传递的独立值时,元组、句柄和类之间几乎是连续的。考虑三种表示复合回报的方法:
(False, "The tricky thing failed!")
{ "status": False, "message": "The tricky thing failed!" }
ResultObject( status=False, message="The tricky thing failed!" )
If there's only one place in your code where you're doing this, the tuple is attractive for its terseness. If you're using this pattern a lot, and passing these result pairs back and forth between different modules, you might "upgrade" to the dict, where the elements have meaningful keys. If these results become a major part of your software design, you might upgrade them again to being instances of an object class. It's a balance between formality and ease of use.
如果在代码中只有一个地方需要这样做,那么tuple的简洁性是很有吸引力的。如果您经常使用这个模式,并且在不同的模块之间来回传递这些结果对,您可能会“升级”到该命令,其中元素有有意义的键。如果这些结果成为软件设计的主要部分,您可以将它们再次升级为对象类的实例。它是形式和使用方便之间的一种平衡。
#2
3
A tuple is simply an immutable sequence, so you can't assign to the individual items of a tuple. One example might be a set of x-y coordinates like (5, 10), (-3, 20), (0, 0)
. If you needed to update some of these coordinates you could recreate the tuples like
tuple只是一个不可变的序列,所以您不能分配给tuple的各个项目。一个例子可能是一组x-y坐标,比如(5,10),(- 3,20),(0,0)。如果你需要更新其中的一些坐标,你可以重新创建元组。
coord = (5, 10)
# Our thing moves
newCoord = (coord[0] + dx, coord[1] + dy)
#3
1
A tuple is supposed to be used for heterogenous data; it is the Python equivalent of C's struct
or Pascal's record
. Appending elements to such a type doesn't make sense, so there is no need for it to be mutable. Contrast with a list, which is for homogenous data:
一个元组应该用于异种数据;它相当于Python的struct或Pascal的记录。将元素附加到这样的类型是没有意义的,所以不需要它是可变的。与同质数据列表对比:
people = [(u'Bob', 24), (u'Sally', 27)]
polygon = [(1, 1), (2, 3), (0, 0)]
#1
4
The coordinates of a square on a chessboard is one example of good use of tuple. I usually use a Python dict, indexed by tuple, to implement a multidimensional array, rather than list-of-lists or the numpy or array modules:
棋盘上正方形的坐标是使用元组的一个很好的例子。我通常使用Python dict(按tuple索引)实现多维数组,而不是列表列表或numpy或数组模块:
board = {}
board[ 3, 6 ] = "black queen"
board[ 0, 0 ] = "white king"
You can't use a mutable (like a list) as a dictionary key, so you need a tuple for this.
不能使用可变的(如列表)作为字典键,因此需要为此使用一个tuple。
Occasionally you find yourself wanting to return multiple values from a function - a boolean to indicate success or failure plus a string describing the failure mode, for instance:
有时你会发现自己想要从一个函数返回多个值——一个布尔值表示成功或失败,加上一个描述失败模式的字符串,例如:
if trickyOperationSucceeds():
return True,"Success!"
return False,"The tricky thing failed!"
This isn't a pattern to use a lot, but sometimes it gets you out of trouble. You could also use a list here; it's only by convention that you'd normally use tuple instead.
这不是一个经常使用的模式,但有时它会让你摆脱麻烦。你也可以在这里使用一个列表;只有按照惯例,你通常才会使用tuple。
When considering how to represent independent values that have to be passed around together, there's almost a continuum between tuples, dicts, and classes. Consider three ways of representing that compound return:
当考虑如何表示必须一起传递的独立值时,元组、句柄和类之间几乎是连续的。考虑三种表示复合回报的方法:
(False, "The tricky thing failed!")
{ "status": False, "message": "The tricky thing failed!" }
ResultObject( status=False, message="The tricky thing failed!" )
If there's only one place in your code where you're doing this, the tuple is attractive for its terseness. If you're using this pattern a lot, and passing these result pairs back and forth between different modules, you might "upgrade" to the dict, where the elements have meaningful keys. If these results become a major part of your software design, you might upgrade them again to being instances of an object class. It's a balance between formality and ease of use.
如果在代码中只有一个地方需要这样做,那么tuple的简洁性是很有吸引力的。如果您经常使用这个模式,并且在不同的模块之间来回传递这些结果对,您可能会“升级”到该命令,其中元素有有意义的键。如果这些结果成为软件设计的主要部分,您可以将它们再次升级为对象类的实例。它是形式和使用方便之间的一种平衡。
#2
3
A tuple is simply an immutable sequence, so you can't assign to the individual items of a tuple. One example might be a set of x-y coordinates like (5, 10), (-3, 20), (0, 0)
. If you needed to update some of these coordinates you could recreate the tuples like
tuple只是一个不可变的序列,所以您不能分配给tuple的各个项目。一个例子可能是一组x-y坐标,比如(5,10),(- 3,20),(0,0)。如果你需要更新其中的一些坐标,你可以重新创建元组。
coord = (5, 10)
# Our thing moves
newCoord = (coord[0] + dx, coord[1] + dy)
#3
1
A tuple is supposed to be used for heterogenous data; it is the Python equivalent of C's struct
or Pascal's record
. Appending elements to such a type doesn't make sense, so there is no need for it to be mutable. Contrast with a list, which is for homogenous data:
一个元组应该用于异种数据;它相当于Python的struct或Pascal的记录。将元素附加到这样的类型是没有意义的,所以不需要它是可变的。与同质数据列表对比:
people = [(u'Bob', 24), (u'Sally', 27)]
polygon = [(1, 1), (2, 3), (0, 0)]