码迷,mamicode.com
首页 > 其他好文 > 详细

序列之元組

时间:2017-10-16 19:34:16      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:color   使用   容器   getattr   字符串   表示   sizeof   index   迭代   

元組:

  和列表功能非常相近的一种容器类型,区别:元组是用圆括号,而列表是中括号,但可以通过list(),tuple()方法进行转换;

  元组是不可变对象,当处理一组对象时,默认是元组类型。

操作符:

1、创建元组:

  工厂函数:tuple(可迭代对象)

  使用圆括号进行创建,只有一个元素的元组,需要在元素后添加逗号,要区分普通的分组操作符

>>>t = (‘a‘)
>>>type(t)
<type ‘str‘>

>>>t = (‘a‘,)
>>>type(t)
<type ‘tuple‘>

2、访问元组的值

  通过切片操作符([start:end:sep]),在里面写上索引值或者索引范围

t = tuple(‘hello,world!‘)
>>>t[1]
e

>>>t[1:5]
(‘e‘, ‘l‘, ‘l‘, ‘o‘)

>>>t[1:]
(‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘,‘, ‘w‘, ‘o‘, ‘r‘, ‘l‘, ‘d‘, ‘!‘)

>>>t[:5:2]
(‘h‘, ‘l‘, ‘o‘)

>>>t[1::2]
(‘e‘, ‘l‘, ‘,‘, ‘o‘, ‘l‘, ‘!‘)

>>t[::2]
(‘h‘, ‘l‘, ‘o‘, ‘w‘, ‘r‘, ‘d‘)

3、更新值

  跟数字和字符串一样,元组也是不可变类型,即不能改变元组的元素。需要进行重新构造一个新元组。

4、删除

  元组不能删除单个元素,只能删除元组本身

#一种方法是进行重置
>>>t = tuple(‘hello,world!‘)
>>>t
(‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘,‘, ‘w‘, ‘o‘, ‘r‘, ‘l‘, ‘d‘, ‘!‘)
>>>t = ‘hello,world!‘
>>>t
hello,world!

#第二中是删除
>>>t = tuple(‘hello,world!‘)
>>>t
(‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘,‘, ‘w‘, ‘o‘, ‘r‘, ‘l‘, ‘d‘, ‘!‘)
>>>del t

 

内置方法:

>>>dir(tuple)
[__add__, __class__, __contains__, __delattr__, __doc__, __eq__, __format__, __ge__, __getattribute__, __getitem__, __getnewargs__, __getslice__, __gt__, 

__hash__, __init__, __iter__, __le__, __len__, __lt__, __mul__, __ne__, __new__, __reduce__, __reduce_ex__, __repr__, __rmul__, __setattr__, __sizeof__,

__str__, __subclasshook__,

count, index]

1、计数

>>>t = tuple(hello,world!)
>>>t
(h, e, l, l, o, ,, w, o, r, l, d, !)

>>>t.count(l)#唯一的参数表示要计数的子串,返回在元组中出现的个数
3

2、查找

>>>t = tuple(hello,world!)
>>>t
(h, e, l, l, o, ,, w, o, r, l, d, !)

‘‘‘tuple.index(sub[,atart[,end]])
在元组中从左到右查找sub第一次出现的的最小的索引值,没有报ValueError错误
‘‘‘
>>>t.index(l)#默认全局查找
2

>>>t.index(l,3,5)#指定返回进行查找
3

>>>t.index(l,5)#指定开始位置
9

序列之元組

标签:color   使用   容器   getattr   字符串   表示   sizeof   index   迭代   

原文地址:http://www.cnblogs.com/Wolverine-python/p/7677989.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!