Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1102037
  • 博文数量: 165
  • 博客积分: 5957
  • 博客等级: 大校
  • 技术积分: 2015
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-24 15:04
文章分类

全部博文(165)

文章存档

2014年(10)

2013年(14)

2012年(9)

2011年(22)

2010年(17)

2009年(17)

2008年(26)

2007年(34)

2006年(16)

我的朋友

分类: LINUX

2008-06-30 15:00:49

Tuple 是不可变 list。 一旦创建了一个 tuple 就不能以任何方式改变它。

日常用法:

__add__        x.__add__(y) <==> x+y
__class__      tuple() -> an empty tuple tuple(sequence) -> tuple initialized from sequence's items If the argument is a tuple, the return value is the same object.
__contains__      x.__contains__(y) <==> y in x
__delattr__      x.__delattr__('name') <==> del x.name
__eq__          x.__eq__(y) <==> x==y
__ge__          x.__ge__(y) <==> x>=y
__getattribute__      x.__getattribute__('name') <==> x.name
__getitem__      x.__getitem__(y) <==> x[y]
__getnewargs__      None
__getslice__      x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported.
__gt__           x.__gt__(y) <==> x>y
__hash__        x.__hash__() <==> hash(x)
__init__        x.__init__(...) initializes x; see x.__class__.__doc__ for signature
__iter__       x.__iter__() <==> iter(x)
__le__          x.__le__(y) <==> x<=y
__len__       x.__len__() <==> len(x)
__lt__        x.__lt__(y) <==> x__mul__      x.__mul__(n) <==> x*n
__ne__        x.__ne__(y) <==> x!=y
__new__       T.__new__(S, ...) -> a new object with type S, a subtype of T
__reduce__     helper for pickle
__reduce_ex__     helper for pickle
__repr__        x.__repr__() <==> repr(x)
__rmul__        x.__rmul__(n) <==> n*x
__setattr__        x.__setattr__('name', value) <==> x.name = value
__str__       x.__str__() <==> str(x)

定义 tuple

>>> t = ("a", "b", "mpilgrim", "z", "example")
>>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> t[0]
'a'
>>> t[-1]
'example'
>>> t[1:3]
('b', 'mpilgrim')

Tuple 没有方法

不能向 tuple 增加、删除、索引元素,但可以查找,如用in

那么使用 tuple 有什么好处呢:

  • Tuple 比 list 操作速度快。如果您定义了一个值的常量集, 并且唯一要用它做的是不断地遍历它, 请使用 tuple 代替 list。
  • 如果对不需要修改的数据进行 “写保护”, 可以使代码更安全。使用 tuple 而不是 list 如同拥有一个隐含的 assert 语句, 说明这一数据是常量。如果必须要改变这些值, 则需要执行 tuple 到 list 的转换 (需要使用一个特殊的函数)。
  • dictionary keys 可以是字符串, 整数和 “其它几种类型” 吗? Tuples 就是这些类型之一。 Tuples 可以在 dictionary 中被用做 key, 但是 list 不行。实际上, 事情要比这更复杂。Dictionary key 必须是不可变的。Tuple 本身是不可改变的, 但是如果您有一个 list 的 tuple, 那就认为是可变的了, 用做 dictionary key 就是不安全的。只有字符串, 整数或其它对 dictionary 安全的 tuple 才可以用作 dictionary key。
  • Tuples 可以用在字符串格式化中。

Tuple 可以转换成 list, 反之亦然。内置的 tuple 函数接收一个 list, 并返回一个有着相同元素的 tuple。而 list 函数接收一个 tuple 返回一个 list。从效果上看, tuple 冻结一个 list, 而 list 解冻一个 tuple。

阅读(1637) | 评论(0) | 转发(0) |
0

上一篇:dictionary

下一篇:list

给主人留下些什么吧!~~