序列
序列是python中的一种数据结构,这种数据结构根据索引来获取序列中的对象
有6种内建序列类:list,tuple,string,unicode,buffer,xrange。 其中xrange比较特殊,是一个生成器
一般来说,具有序列结构的数据类型都可以使用:
index,len,max,min,in,+,*,切片
1 >>> a='Iloveyou' 2 >>> len(a) 3 8 4 >>> max(a) 5 'y' 6 >>> min(a) 7 'I' 8 >>> type(a) 910 >>> id(a)11 14066659518574412 >>> id('Iloveyou')13 14066659518574414 >>> bool('o' in a)15 True16 >>> a+a17 'IloveyouIloveyou'18 >>> a*319 'IloveyouIloveyouIloveyou'20 >>> a[1:4]21 'lov'22 >>> a.index('y')23 524 >>> a[5]25 'y'
切片操作
对具有序列结构的数据来说,切片操作的方法:consequence[start_index:end_index:step]
start_index: 表示是第一个元素对象,正索引位置默认为0;负索引位置默认为 -len(consequence)
end_index: 表示最后一个元素对象,正索引位置默认len(consequence)-1;负索引位置默认 -1
step: 表示取值的步长,默认为1,步长不能为0
[注意]对于序列结构数据来说,索引和步长都具有正负两个值,分别表示左右两个方向取值。索引的正方向从左往右取值,起始位置为0;负方向从右往左取值,起始位置为-1。因此任意一个序列结构数据的索引范围为 -len(consequence) 到 len(consequence)-1 范围内的连续整数。
1 >>> 2 >>> a=[1,2,3,4,5,6,7] 3 >>> type(a) 45 >>> a[len(a)-1] 6 7 7 >>> a[-len(a)] 8 1 9 >>> a[-len(a)]10 111 >>> a[len(a)]12 Traceback (most recent call last):13 File " ", line 1, in 14 IndexError: list index out of range
其中a[len(a)-1]等同于a[-1],a[-len(a)]等同于a[0]
使用冒号对序列进行切片取值时,你所输入的无论是start_index或end_index,都不必局限于-len(a) 和len(a)-1 之间,因为只有当你输入的索引号处于这个区间时才真正有效,而当你输入的索引号超出这个范围,python会自动将start_index 或 end_index 设定为缺省值(即第一个对象和最后一个对象)
[注意]一定要记住,end_index其实是你第一个不想要获取的对象的索引,所以a[0:-1]是取不到a[-1]的,所以如果要使得切片片段包含end_index位置的对象,请缺省end_index,或者输入一个超出end_index范围的值。
利用步长对序列进行倒序取值
在切片运算中,步长为正,表示从左至右,按照索引值与起始位置索引之差可以被步长整除的规律取值;当步长为负,则表示从右至左,按照按照索引值与起始位置索引之差可以被步长整除的规律取值。
根据这个特性,我们可以很方便对某个序列进行倒序取值,这个方法比reverse方法更方便,且适用于没有reverse方法的字符串和元组。相对reverse而言,切片的方法不会改变列表的结构,所以这是在实际应用中比较有用的一个技巧。
1 >>> a=[1,2,3,4,5,6,7,] 2 >>> a=[1,2,3,4,5,6,7] 3 >>> b=(1,2,3,4,5,6,7) 4 >>> type(b) 56 >>> type(a) 7 8 >>> c='Let me show you a little thing' 9 >>> 10 >>> a[::-1]11 [7, 6, 5, 4, 3, 2, 1]12 >>> b[::-1]13 (7, 6, 5, 4, 3, 2, 1)14 >>> c[::-1]15 'gniht elttil a uoy wohs em teL'16 >>> a17 [1, 2, 3, 4, 5, 6, 7]18 >>> b19 (1, 2, 3, 4, 5, 6, 7)20 >>> c21 'Let me show you a little thing'22 >>> a.reverse()23 >>> a24 [7, 6, 5, 4, 3, 2, 1]
更新列表
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 list = ['physics','chemistry',1997,2000] 5 print "Value available at index 2 :" 6 print list[2] 7 list[2]=2001 8 print "New value available at index 2 :" 9 print list[2] # 结果10 [root@localhost 20170120]# python xulie.py 11 Value available at index 2 :12 199713 New value available at index 2 :14 2001
删除列表元素
#!/usr/bin/env python# -*- coding:utf-8 -*-list = ['physics','chemistry',1997,2000]print listdel list[2]print "After deleting value at index 2 : "print list#结果[root@localhost 20170120]# python xulie.py ['physics', 'chemistry', 1997, 2000]After deleting value at index 2 : ['physics', 'chemistry', 2000]
创建list有很多方法:
1.使用一对方括号创建一个空的list:[]
2.使用一对方括号,用','隔开里面的元素:[a, b, c], [a] 3.Using a list comprehension:[x for x in iterable] 4.Using the type constructor:list() or list(iterable)'''def create_empty_list():'''Using a pair of square brackets to denote the empty list: [].'''return []def create_common_list():'''Using square brackets, separating items with commas: [a], [a, b, c].'''return ['a', 'b', 'c', 1, 3, 5]def create_common_list2():'''Using a list comprehension: [x for x in iterable].'''return [x for x in range(1, 10)]def str_to_list(s):'''Using a string to convert list'''if s != None:return list(s)else:return []def main():test_listA = create_empty_list()print(test_listA)print('#' * 50)test_listB = create_common_list()print(test_listB)print('#' * 50)test_listC = create_common_list2()print(test_listC)print('#' * 50)test_str = 'i want to talk about this problem!'test_listD = str_to_list(test_str)print(test_listD)if __name__ == '__main__':main()
2、tuple 转 list
#!/usr/bin/env python# -*- coding:utf-8 -*-aTuple=(12,3,'a','yy')aList=list(aTuple)print "aTyple type is: ",type(aTuple)print "aList type is: ",type(aList)print "aList's value is: ",aList
运行结果
[root@localhost 20170120]# python tuple2list.py aTyple type is:aList type is: aList's value is: [12, 3, 'a', 'yy']
3、tuple与list相似,但是tuple不能修改,tuple使用小括号,列表用方括号
tuple创建,只需在括号中添加元素,并使用逗号隔开即可
tuple创建只包含一个元素时,需在元素后面添加逗号
tup1=(50,)
1 >>> tup1 = ("all")2 >>> print tup13 all4 输出字符串 all,这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号。5 所以,如果元组只有1个元素,就必须加一个逗号,防止被当作括号运算:6 >>> tup1 = ("all",)7 >>> print tup18 ('all',)9 >>>
[root@localhost 20170120]# cat tuple.py#!/usr/bin/env python# -*- coding:utf-8 -*-tup1=('physics','chemistry',1997,2000);tup2=(1,2,3,4,5,6,7,8,9);print "tup1[0]:",tup1[0];print "tup2[1:5]:",tup2[1:5];[root@localhost 20170120]# python tuple.pytup1[0]: physicstup2[1:5]: (2, 3, 4, 5)
修改元组
元组中的元素不能修改,但可以对元组进行连接组合
#代码#!/usr/bin/env python# -*- coding:utf-8 -*-tup1=(12,34.56)tup2=('abc','xyz')tup3=tup1+tup2print tup3#运行结果[root@localhost 20170120]# python tuple.py(12, 34.560000000000002, 'abc', 'xyz')
删除元组
#!/usr/bin/env python# -*- coding:utf-8 -*-tup1=('physics','chemistry',1997,2000);print tup1del tup1print "After deleting tup1:"print tup1#执行结果[root@localhost 20170120]# python tuple.py('physics', 'chemistry', 1997, 2000)After deleting tup1:Traceback (most recent call last): File "tuple.py", line 8, inprint tup1NameError: name 'tup1' is not defined
#!/usr/bin/env python# -*- coding:utf-8 -*-list01=['runoob',786,2.23,'john',70.2]list02=[123,'john']print list01print list02print "列表截取"print list01[0]print list01[-1]print list01[0:3]print "列表重复"print list01 * 2print "列表组合"print list01 + list02print "获取列表长度"print len(list01)print "删除列表元素"del list02[0]print list02print "元素是否存在于列表中"print 'john' in list02print "迭代"for i in list01: print iprint "比较两个列表的元素"print cmp(list01,list02)print "列表最大/最小值"print max([0,1,2,3,4])print min([0,1])print "将元组转换为列表"aTuple = (1,2,3,4)list03=list(aTuple)print list03print "在列表末尾添加新的元素"list03.append(5)print list03print "在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)"list03.extend(list01)print list03print "统计某个元素在列表中出现的次数"print list03.count(1)print "从列表中找出某个值第一个匹配项的索引位置"print list03.index('john')print "将对象插入列表"list03.insert(0,'hello')print list03print "移除列表中的一个元素(默认最后一个元素),并且返回该元素的值"print list03.pop(0)print list03print "移除列表中某个值的第一个匹配项"list03.remove(1)print list03print "反向列表中元素"list03.reverse()print list03print "对原列表进行排序"list03.sort()print list03#结果[root@localhost 20170120]# python xulie.py ['runoob', 786, 2.23, 'john', 70.200000000000003][123, 'john']列表截取runoob70.2['runoob', 786, 2.23]列表重复['runoob', 786, 2.23, 'john', 70.200000000000003, 'runoob', 786, 2.23, 'john', 70.200000000000003]列表组合['runoob', 786, 2.23, 'john', 70.200000000000003, 123, 'john']获取列表长度5删除列表元素['john']元素是否存在于列表中True迭代runoob7862.23john70.2比较两个列表的元素1列表最大/最小值40将元组转换为列表[1, 2, 3, 4]在列表末尾添加新的元素[1, 2, 3, 4, 5]在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)[1, 2, 3, 4, 5, 'runoob', 786, 2.23, 'john', 70.200000000000003]统计某个元素在列表中出现的次数1从列表中找出某个值第一个匹配项的索引位置8将对象插入列表['hello', 1, 2, 3, 4, 5, 'runoob', 786, 2.23, 'john', 70.200000000000003]移除列表中的一个元素(默认最后一个元素),并且返回该元素的值hello[1, 2, 3, 4, 5, 'runoob', 786, 2.23, 'john', 70.200000000000003]移除列表中某个值的第一个匹配项[2, 3, 4, 5, 'runoob', 786, 2.23, 'john', 70.200000000000003]反向列表中元素[70.200000000000003, 'john', 2.23, 786, 'runoob', 5, 4, 3, 2]对原列表进行排序[2, 2.23, 3, 4, 5, 70.200000000000003, 786, 'john', 'runoob']
参考:
1、http://www.cnblogs.com/ifantastic/archive/2013/04/15/3021845.html