无聊之人--除了技术,还是技术,你懂得
分类: Python/Ruby
2011-06-14 00:58:15
3.3. Introducing Tuples
A tuple is an immutable list. A tuple can not be changed in any way once it is created.
不变列表是不能改变的列表。不变列表一旦创建,就不能通过任何方式改变
Example 3.15. Defining a tuple
例3.15 定义一个不变列表
A tuple is defined in the same way as a
list, except that the whole set of elements is enclosed in parentheses
instead of square brackets. 不变列表的定义同列表的定义类似,除了不变列表的元素集通过括号来封装而不是使用方括号。 The elements of a tuple have a defined
order, just like a list. Tuples indices are zero-based, just like a list, so
the first element of a non-empty tuple is always t[0]. 不变列表的元素也有一个定义时顺序,同列表类似。不变列表也是从0开始索引,同列表一样,因此非空列表的第一个元素总是Li[0]. Negative indices count from the end of
the tuple, just as with a list. 同列表类似,不变列表的反向索引也是从反向开始计数索引元素的 Slicing works too, just like a list.
Note that when you slice a list, you get a new list; when you slice a tuple,
you get a new tuple. 切片同样使用与不变列表。值得注意的是,当你对一个列表进行切片时,返回值为一个新列表,当你对不变列表进行切片时,你得到一个tuple.
Example 3.16. Tuples Have No Methods
例3.16 tuples不具有任何方法
You can't add elements to a tuple.
Tuples have no append or extend method. Tuple不能添加元素,同样它也不具有append或是extend方法。 You can't remove elements from a tuple.
Tuples have no remove or pop method. 你不能从tuple中移除元素,它也没有remove或是pop方法。 You can't find elements in a tuple.
Tuples have no index method. 你不在能tuple中查找元素,不具有index方法。 You can, however, use in to see if an element exists in
the tuple. 然而你可以用 in 来测试tuple是否存在一个元素。
So what are tuples good for?
那么tuple有什么好处呢?
|
|
|
Tuples can be converted into lists, and vice-versa. The built-in tuple function takes a list and returns a tuple with the same elements, and the list function takes a tuple and returns a list. In effect, tuple freezes a list, and list thaws a tuple.tuple和列表可以相互转化。内置tuple函数将一个列表转换成一个含有相同元素的tuple,而list函数则将一个tuple转换成一个列表。事实上tuple冻结了list,list解冻了了一个tuple |
|