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

本文介绍了Python中元组的基本概念及使用方法,包括如何创建单元素元组、如何使用元组进行数据操作等。通过示例代码展示了元组的定义、长度获取及元素访问等关键特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

含有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
>>>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值