天天看点

python 学习笔记05: tuple(元组)类型的操作

# -*- coding:UTF-8 -*-

'''
    今天学习python中用数据类型 tuple(元组)。
    学习一个类型,最好的办法肯定是了解下这个类型中包含了那些方法与成员变量
    然后对每个方法的具体进行调用,业精于去荒于嬉,点滴积累,用久必深

    Help on class tuple in module __builtin__:

class tuple(object)
 |  tuple() -> empty tuple
 |  tuple(iterable) -> tuple initialized from iterable's items
 |  
 |  If the argument is a tuple, the return value is the same object.
 |  
 |  Methods defined here:
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x
 |  
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |  
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __getnewargs__(...)
 |  
 |  __getslice__(...)
 |      x.__getslice__(i, j) <==> x[i:j]
 |      
 |      Use of negative indices is not supported.
 |  
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |  
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |  
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |  
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |  
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |  
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |  
 |  __mul__(...)
 |      x.__mul__(n) <==> x*n
 |  
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |  
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |  
 |  __rmul__(...)
 |      x.__rmul__(n) <==> n*x
 |  
 |  count(...)
 |      T.count(value) -> integer -- return number of occurrences of value
 |  
 |  index(...)
 |      T.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

'''





# 先打印tuple类型的帮助文档看看
# 可以重帮助文档(如上)看到,tuple的操作与list基本类似,
# 但是不在有插入、删除这些方法了
help("tuple")

# 定义一个元组并初始化=》需要注意的是,一旦一个元组被初始化则不可以被修改
testtuple = ("annle",2,4,'bella',[3,5,6,8,23])
print(testtuple)

# 访问元组中的元素

numlist = testtuple[-1]  # 通过下标访问元组中的元素
print(numlist)   # [3, 5, 6, 8, 23]

# 还可以像下面这样直接获取到tuple对象中list元素的某个值
i0 = testtuple[4][0]
print(i0)  # 3


# 看下tuple的切片处理
slicetuple = testtuple[0:3] # 我们期待获取tuple中下标为0、1、2的元素,并保存到一个tuple中
print(slicetuple)  #('annle', 2, 4) ==》从打印结果也可以看出,slicetuple是一个元组类型

# 元素个数:len()
print(len(slicetuple)) # 3 看到有三个元素

# 通过循环去打印tuple中的每个元素
for item in testtuple :
    print(item)

# 或者也可以通过下标
for i in range(0,len(testtuple)):
    print(testtuple[i])