python之tuple

1、python元组

Python的元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号,列表使用方括号。

#创建元组
>>> tuple2 = 123,456,'hello' #任意无符号的对象,以逗号隔开,默认为元组
>>> type(tuple2)
<class 'tuple'>
>>> tuple1 = ('a','b','c')
>>> type(tuple1)
<class 'tuple'> >>> tuple3 = () #创建空元组 >>> tuple4 = (10)
>>> type(tuple4)
<class 'int'>
>>> tuple4 = (10,) #在创建元组中只包含一个元素时,需要在元素后面添加逗号
>>> type(tuple4)
<class 'tuple'>

2、访问元组,组合元组,删除元组

#访问元组与访问列表一样,使用下标索引来访问元组中的值
>>> tup1 = ('number','string','list','tuple','dictionary')
>>> tup1[:]
('number', 'string', 'list', 'tuple', 'dictionary')
>>> tup1[3]
'tuple'
>>> tup1[1:4]
('string', 'list', 'tuple') #链接组合元组
>>> tup2 = (1,2,3,4,5)
>>> tup3 = tup1+tup2
>>> tup3
('number', 'string', 'list', 'tuple', 'dictionary', 1, 2, 3, 4, 5) #删除元组,使用del语句来删除整个元组
>>> del tup3

3、元组运算符

与字符串一样,元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组。

Python 表达式 结果 描述
len((1, 2, 3)) 3 计算元素个数
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) 连接
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') 复制
3 in (1, 2, 3) True 元素是否存在
for x in (1, 2, 3): print x, 1 2 3 迭代

4、元组内置函数与方法

In [14]: tup1 = (1,2,3)     #创建元组
In [15]: tup2 = ('a','b','c') In [16]: cmp(tup1,tup2) #比较元组
Out[16]: -1
In [17]: cmp(tup2,tup1)
Out[17]: 1 In [18]: len(tup1) #统计元组元素个数
Out[18]: 3 In [19]: max(tup1) #返回元组元素最大值
Out[19]: 3
In [20]: max(tup2)
Out[20]: 'c' In [21]: min(tup2) #返回元组元素最小值
Out[21]: 'a' In [22]: list1 = [33,22,11]
In [23]: tuple(list1) #将列表转换成元组
Out[23]: (33, 22, 11) In [24]: tup2.count('a') #统计元组中元素出现的次数
Out[24]: 1 In [25]: tup2.index('a') #显示元组中元素的索引
Out[25]: 0
In [26]: tup2.index('c')
Out[26]: 2
上一篇:Js获取客户端用户Ip地址


下一篇:Java学习笔记(二)——类和对象