码迷,mamicode.com
首页 > 编程语言 > 详细

python——tuple元组

时间:2016-09-29 02:07:55      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

>>> 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)
>>> 

 

python——tuple元组

标签:

原文地址:http://www.cnblogs.com/13224ACMer/p/5918474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!