简明 Python 教程 -- 第9章 数据结构
2007-03-29 11:52:35 来源:WEB开发网核心提示: 例9.2 使用元组#!/usr/bin/python# Filename: using_tuple.pyzoo = ('wolf', 'elephant', 'penguin')print 'Number of animals in
例9.2 使用元组
#!/usr/bin/python
# Filename: using_tuple.py
zoo = ('wolf', 'elephant', 'penguin')
print 'Number of animals in the zoo is', len(zoo)
new_zoo = ('monkey', 'dolphin', zoo)
print 'Number of animals in the new zoo is', len(new_zoo)
print 'All animals in new zoo are', new_zoo
print 'Animals brought from old zoo are', new_zoo[2]
print 'Last animal brought from old zoo is', new_zoo[2][2](源文件:code/using_tuple.py)
输出
$ python using_tuple.py
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
Last animal brought from old zoo is penguin它如何工作
变量zoo是一个元组,我们看到len函数可以用来获取元组的长度。这也表明元组也是一个序列。
由于老动物园关闭了,我们把动物转移到新动物园。因此,new_zoo元组包含了一些已经在那里的动物和从老动物园带过来的动物。回到话题,注意元组之内的元组不会失去它的身份。
我们可以通过一对方括号来指明某个项目的位置从而来访问元组中的项目,就像我们对列表的用法一样。这被称作 索引 运算符。我们使用new_zoo[2]来访问new_zoo中的第三个项目。我们使用new_zoo[2][2]来访问new_zoo元组的第三个项目的第三个项目。
更多精彩
赞助商链接
