Python 基础数据类型之tuplu

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

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

1、元组的定义

tuple1 = ("hello", "world", 100, 200)
tuple2 = ()  # 定义空元祖
tuple3 = tuple()  # 定义空元祖
print type(tuple1), type(tuple2), type(tuple3)

#运行结果:
<type 'tuple'> <type 'tuple'> <type 'tuple'>

 2、访问元组

tup1 = ("hello", "world", 100, 200);
tup2 = (1, 2, 3, 4, 5, 6, 7 );

print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]

#运行结果
tup1[0]:  hello
tup2[1:5]:  (2, 3, 4, 5)

3、修改/删除元组

元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,如下实例:

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');

# 以下修改元组元素操作是非法的。
# tup1[0] = 100;

# 创建一个新的元组
tup3 = tup1 + tup2;
print tup3;

#运行结果
(12, 34.56, 'abc', 'xyz')

元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如下实例:

tup = ("hello", "world", 100, 200);
#del = tup[2] # 该操作是不合法的
del tup;
print "After deleting tup : "
print tup;

#运行结果:
After deleting tup : 
    print tup;
NameError: name 'tup' is not defined

4、元组常用方法

list.index(obj) #从列表中找出某个值第一个匹配项的索引位置

list.count(obj) #统计某个元素在列表中出现的次数

5、元组的内置函数

cmp(tuple1, tuple2) #比较两个元组元素。

len(tuple) #计算元组元素个数。

max(tuple) #返回元组中元素最大值。

min(tuple) #返回元组中元素最小值。

tuple(seq) #将列表转换为元组。

 

posted @ 2017-11-25 19:18  YangYongming  阅读(543)  评论(0编辑  收藏  举报