python——tuple元组

本文详细介绍了Python中元组(tuple)的基本概念与用法,包括元组的定义、特性及与列表的区别,通过实例展示了如何创建元组、元组不可变性的特点以及如何通过切片进行元素的操作。
>>> dir(tuple)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
>>> tuple
<type 'tuple'>
>>> tuple_1=(1,2,3,4,5,6)
>>> tuple_1
(1, 2, 3, 4, 5, 6)
>>> tuple[0]=1

Traceback (most recent call last):
  File "<pyshell#77>", line 1, in <module>
    tuple[0]=1
TypeError: 'type' object does not support item assignment
>>> 

tuple就是元组的类型,他和列表相近,但是也有很大的区别,如上,tuple不能修改元素,如果修改就会报错,如上

 

 

判断一个列表可以看中括号,但是看元组的依据主要是逗号

eg:如果我们只是需要一个元素,如果不加上逗号,那么会被默认为一个整数类型,如果在后面加上一个逗号,就会被认为是tuple

>>> tuple_2=(1)
>>> tuple_2
1
>>> type(tuple_2)
<type 'int'>
>>> tuple_3=(1,)
>>> tuple_3
(1,)
>>> type(tuple_3)
<type 'tuple'>
>>> 

但是对于空的加不加逗号就不影响了

>>> list1=[]
>>> type(list1)
<type 'list'>
>>> tuple1=()
>>> type(tuple1)
<type 'tuple'>
>>> 

 

 

 

因为元组不能更改,所有列表里面的3中添加和删除都不能使用

但是我们可以通过切片进行增加和删除

>>> 
>>> tmp1=(1,2,4,5,6)
>>> tmp1=tmp1(:2)
SyntaxError: invalid syntax
>>> tmp1=tmp1[:2]+tmp[3:]

Traceback (most recent call last):
  File "<pyshell#103>", line 1, in <module>
    tmp1=tmp1[:2]+tmp[3:]
NameError: name 'tmp' is not defined
>>> tmp1=tmp1[:2]+tmp1[3:]
>>> tmp1
(1, 2, 5, 6)
>>> tmp1=tmp1[:2]+(4,)  #这里注意加上的单个元素一定要加上逗号
>>> tmp1
(1, 2, 4)
>>> 

 

转载于:https://www.cnblogs.com/13224ACMer/p/5918474.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值