基础数据类型-tuple
Python中,元组tuple与list类似,不同之处在于tuple的元素不能修改,tuple使用(),list使用[],
(1)元组的创建使用(),需要注意的是创建包含一个元素的元组:
1 tuple_number = () 2 tuple_number = (1, ) #创建一个元素的元组,在元素后加逗号 3 print("type of (1) is:", type((1))) #(1)的类型是整形 4 5 type of (1) is: <class 'int'>
(2)元组的索引,切片,检查成员,加,乘
1 #索引 2 tuple_number = (1, 2, 3, 4, 5) 3 print("tuple_number[2]:", tuple_number[2]) 4 #切片 5 print("tuple_number[1:4]:", tuple_number[1:4])#index = 4的元素不包含 6 #检查成员 7 if 6 in tuple_number: 8 print("6 is in tuple_number") 9 else: 10 print("6 is not in tuple_number") 11 #加 12 tuple_name = ('John', 'Paul') 13 print("tuple_number plus tuple_name:", tuple_number + tuple_name) 14 #乘 15 print("tuple_number * 2:", tuple_number * 2)
1 tuple_number[2]: 3 2 tuple_number[1:4]: (2, 3, 4) 3 6 is not in tuple_number 4 tuple_number plus tuple_name: (1, 2, 3, 4, 5, 'John', 'Paul') 5 tuple_number * 2: (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
(3)tuple的遍历和list一样: for number in tuple_number:print(number)
(4)与list一样,tuple也有函数:len(),max(),min(),tuple()
(5)由于tuple的元素不允许修改,tuple的内置方法只有count(),index()
1 #方法 2 tuple_number = (1, 1, 2, 2, 2, 3, 3, 3, 3) 3 print("count of 2 in tuple_number:", tuple_number.count(2)) #元素出现的次数 4 print("index of first 3:", tuple_number.index(3)) #元素第一次出现的位置
1 count 2 in tuple_number: 3 2 index of first 3: 5
(6)最后看看tuple类的定义:
1 class tuple(object): 2 """ 3 tuple() -> empty tuple 4 tuple(iterable) -> tuple initialized from iterable's items 5 6 If the argument is a tuple, the return value is the same object. 7 """ 8 def count(self, value): # real signature unknown; restored from __doc__ 9 """ T.count(value) -> integer -- return number of occurrences of value """ 10 return 0 11 12 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ 13 """ 14 T.index(value, [start, [stop]]) -> integer -- return first index of value. 15 Raises ValueError if the value is not present. 16 """ 17 return 0