`

Python学习笔记(七): tuple元组

 
阅读更多
元组和列表十分类似,只不过元组和字符串一样是 不可变的。

含有0个或1个项目的元组。一个空的元组由一对空的圆括号组成,如myempty = ()。然而,含有单个元素的元组就不那么简单了。你必须在第一个(唯一一个)项目后跟一个逗号,这样Python才能区分元组和表达式中一个带圆括号的对象。即如果你想要的是一个包含项目2的元组的时候,你应该指明singleton = (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]);



结果

>>>
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
>>>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics