python数据类型之元组

python数据类型之元组

数据类型—元组tuple

特性:有序,不可变的数据类型,可以存所有数据类型的任意多个数据,是可迭代的数据类型,又称只读列表(元组本身不可变,但元组内有可变的元素,这些元素是可以改变的)

官方帮助文档

  1. Help on class tuple in module builtins: 
  2.  
  3. class tuple(object) 
  4. | tuple() -> empty tuple 
  5. | tuple(iterable) -> tuple initialized from iterable's items 
  6. |  
  7. | If the argument is a tuple, the return value is the same object. 
  8. |  
  9. | Methods defined here: 
  10. | count(...) 
  11. | T.count(value) -> integer -- return number of occurrences of value 
  12. |  
  13. | index(...) 
  14. | T.index(value, [start, [stop]]) -> integer -- return first index of value. 
  15. | Raises ValueError if the value is not present. 
  16.  

创建元组

tuple() -> empty tuple
| tuple(iterable) -> tuple initialized from iterable's items

多个无符号的对象,以逗号隔开,默认为元组

>>> a = 1,2,['a','b']
>>> a
(1, 2, ['a', 'b'])

元组中只包含一个元素时,需在末尾添加逗号
>>> a = (1,)
>>> a
(1,)
>>> a = (1)  不加逗号就不是元组
>>> a
1

tuple(iterable) -> tuple initialized from iterable's items
>>> a = tuple('abcde')  # 需要是可迭代的数据类型,否则报错
>>> a
('a', 'b', 'c', 'd', 'e')

>>> a = tuple(123)  # 报错
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    a = tuple(123)
TypeError: 'int' object is not iterable

元组的方法

['count', 'index']

查询

通过索引查询操作;正向递增,反向递减,从左往右从0开始,最末尾的为-1。
L = ('a', 'b', 1, 2, ['c', 'd'])
      0    1   2  3       4
L[1] = ‘b’
L[4] = ('c', 'd')

L[索引号]就可以取出所对应的值

切片:L[M:N:K]M和N为索引号,K为步长。从M到N(包括M不包括N)根据步长K取值。
M和N缺失时代表至开头和至结尾(包括最后一个值)
K为负数时代表从右往左开始取值。(当K为负值时,M>N)
>>> L = ('a', 'b', 1, 2, ['c', 'd'])
>>> L[:-2:2]
['a', 1]

>>> L = ('a', 'b', 1, 2, ['c', 'd'])
>>> L[-1:-3:-1]
[['c', 'd'], 2]

a= (1,2,3,4,5,'a','c',11,23,22,55)
print(a[10:0:-1])    
>>>(55, 22, 23, 11, 'c', 'a', 5, 4, 3, 2)
a= (1,2,3,4,5,'a','c',11,23,22,55)
print(a[0:10:-1])    # K为负值时,M<N,返回一个空列表
>>>()

元组本身不可变,但元组内有可变的元素,这些元素是可以改变的

元组本身的元素不能改变
>>> a = ('a', 'b', 1, 2, ['c', 'd'])  
>>> a[-1] = 2
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    a[-1] = 2
TypeError: 'tuple' object does not support item assignment

元组中的可变元素中的数据可以改变
>>> a[-1][0] = 8
>>> a
('a', 'b', 1, 2, [8, 'd'])

不能对元组内部的第一层元素进行修改和删除,但是可以删除元组
>>> del a
>>> a
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    a
NameError: name 'a' is not defined

元组的其他方法

>> dir(tuple)" class="language->>> dir(tuple) hljs ruby">['count', 'index']

>>> a = ('c','g', 'b', 'g', 2, ['c', 'd'])
>>> a.count('g')  # 统计元组中某个元素的个数
2
>>> a.index('g')  # 查找某个元素第一次出现的位置索引
1

元组的循环

>>> a = ('c','g', 'b', 'g', 2, ['c', 'd'])
>>> for index, k in enumerate(a):
    print(index,k)	
0 c
1 g
2 b
3 g
4 2
5 ['c', 'd']

猜你喜欢

转载自www.cnblogs.com/james201133002/p/9437004.html