sweli 发表于 2018-8-14 08:13:51

Python数据结构方法简介三————元组

  Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可,元组中只包含一个元素时,需要在元素后面添加逗号。
  元组与列表的区别:
  1、元组不可变,列表可变。
  2、元组比列表更安全,操作速度更快。
  一、创建元组
tuple1=(1,2,3,4)  
tuplt2=('a','b','c','d')
  二、访问元组
  元组的访问与列表相同,都是利用索引值来进行访问。
tuple1  
2
  
tuple1[-1]
  
如果超出索引范围,python会报一个异常。
  
tuple1
  
Traceback (most recent call last):
  
Python Shell, prompt 4, line 1
  
IndexError: tuple index out of range
  索引错误:元组的索引超出范围
  三、切片
  元组的切片与列表相同,只包括起始位置,不包括结束位置。
tuple1  
(1, 2)
  当切片时起始位置超出索引范围时,会返回一个空元组。
tuple1  
()
  四、元组的方法
  由于元组不可修改,所以元组的方法非常少。
  1.count 统计元素出现的次数,返回一个整数
  T.count(value) -> integer -- return number of occurrences of value
tuple1.count(1)  
1
  2.index 查找某个元素的索引位置
  T.index(value, ]) -> integer -- return first index of value. Raises ValueError if the value is not present.
tuple1.index(2)  
1
  五、元组与列表的转换
1元组转换为列表  
print tuple1
  
(1, 2, 3, 4)
  
test=list(tuple1)
  
print test
  

  
2.列表装换为元组
  
print test
  

  
tuple1=tuple(test)
  
print tuple1
  
(1, 2, 3, 4)
页: [1]
查看完整版本: Python数据结构方法简介三————元组