首页 > 代码库 > 【python】元组
【python】元组
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> tuple_1 = (1,‘a‘,2,"b",3,‘c‘)
>>> tuple_1
(1, ‘a‘, 2, ‘b‘, 3, ‘c‘)
>>> tuple_1 = (1,‘a‘,(2,"b"),3,‘c‘)
>>> tuple_1
(1, ‘a‘, (2, ‘b‘), 3, ‘c‘)
>>> tuple_1[0]
1
>>> tuple_1[2][0]
2
>>> tuple_1[2:]
((2, ‘b‘), 3, ‘c‘)
>>> tuple_1[:2]
(1, ‘a‘)
>>> tuple_1[:]
(1, ‘a‘, (2, ‘b‘), 3, ‘c‘)
>>> tuple_2=tuple_1[:]
>>> tuple_2[0]=4
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
tuple_2[0]=4
TypeError: ‘tuple‘ object does not support item assignment
>>> tmp=(23)
>>> type(tmp)
<class ‘int‘>
>>> tmp2=1,2
>>> type(tmp2)
<class ‘tuple‘>
>>> #是不是tuple类型关键是逗号而不是小括号
>>> tmp3=[]
>>> type(tmp3)
<class ‘list‘>
>>> #是不是list类型只要看有没有中括号
>>> tmp4=()
>>> type(tmp4)
<class ‘tuple‘>
>>> #如果只有小括号而无逗号就是空元组
>>> tmp5=(1,)
>>> type(tmp5)
<class ‘tuple‘>
>>> tmp5
(1,)
>>> tmp6=1,
>>> type(tmp6)
<class ‘tuple‘>
>>> 6*(6,)
(6, 6, 6, 6, 6, 6)
>>> type(6,)
<class ‘int‘>
>>> tmp=(‘扫地僧‘,‘张三丰‘,"风清扬","石破天")
>>> tmp=tmp[:2]+(‘郭靖‘,)+tmp[2:]
>>> tmp
(‘扫地僧‘, ‘张三丰‘, ‘郭靖‘, ‘风清扬‘, ‘石破天‘)
>>> #原来的tmp还存在,但无名称标签贴上,会被python自动回收
>>> del tmp
>>> tmp
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
tmp
NameError: name ‘tmp‘ is not defined
>>> #python有回收机制,无需用del去主动删除,无标签贴上时会自动回收
【python】元组