zoukankan      html  css  js  c++  java
  • python 序列

    序列

    序列是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)
     9 <type 'str'>
    10 >>> id(a)
    11 140666595185744
    12 >>> id('Iloveyou')
    13 140666595185744
    14 >>> bool('o' in a)
    15 True
    16 >>> a+a
    17 'IloveyouIloveyou'
    18 >>> a*3
    19 'IloveyouIloveyouIloveyou'
    20 >>> a[1:4]
    21 'lov'
    22 >>> a.index('y')
    23 5
    24 >>> 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)
     4 <type 'list'>
     5 >>> a[len(a)-1]
     6 7
     7 >>> a[-len(a)]
     8 1
     9 >>> a[-len(a)]
    10 1
    11 >>> a[len(a)]
    12 Traceback (most recent call last):
    13   File "<stdin>", line 1, in <module>
    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)
     5 <type 'tuple'>
     6 >>> type(a)
     7 <type 'list'>
     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 >>> a
    17 [1, 2, 3, 4, 5, 6, 7]
    18 >>> b
    19 (1, 2, 3, 4, 5, 6, 7)
    20 >>> c
    21 'Let me show you a little thing'
    22 >>> a.reverse()
    23 >>> a
    24 [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 1997 13 New value available at index 2 : 14 2001

     删除列表元素

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    list = ['physics','chemistry',1997,2000]
    
    print list
    del 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:  <type 'tuple'>
    aList type is:  <type 'list'>
    aList's value is:  [12, 3, 'a', 'yy']

     3、tuple与list相似,但是tuple不能修改,tuple使用小括号,列表用方括号

           tuple创建,只需在括号中添加元素,并使用逗号隔开即可

           tuple创建只包含一个元素时,需在元素后面添加逗号

          tup1=(50,)

    1 >>> tup1 = ("all")
    2 >>> print tup1
    3 all
    4 输出字符串 all,这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号。
    5 所以,如果元组只有1个元素,就必须加一个逗号,防止被当作括号运算:
    6 >>> tup1 = ("all",)
    7 >>> print tup1
    8 ('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.py
    tup1[0]: physics
    tup2[1:5]: (2, 3, 4, 5)

      修改元组

      元组中的元素不能修改,但可以对元组进行连接组合

    #代码
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    tup1=(12,34.56)
    tup2=('abc','xyz')
    
    tup3=tup1+tup2
    print 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 tup1
    del tup1
    print "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, in <module>
        print tup1
    NameError: name 'tup1' is not defined
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    list01=['runoob',786,2.23,'john',70.2]
    list02=[123,'john']
    
    print list01
    print list02
    
    print "列表截取"
    print list01[0]
    print list01[-1]
    print list01[0:3]
    
    print "列表重复"
    print list01 * 2
    
    print "列表组合"
    print list01 + list02
    
    print "获取列表长度"
    print len(list01)
    
    print "删除列表元素"
    del list02[0]
    print list02
    
    print "元素是否存在于列表中"
    print 'john' in list02
    
    print "迭代"
    for i in list01:
       print i
    
    print "比较两个列表的元素"
    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 list03
    
    print "在列表末尾添加新的元素"
    list03.append(5)
    print list03
    
    print "在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)"
    list03.extend(list01)
    print list03
    
    print "统计某个元素在列表中出现的次数"
    print list03.count(1)
    
    print "从列表中找出某个值第一个匹配项的索引位置"
    print list03.index('john')
    
    print "将对象插入列表"
    list03.insert(0,'hello')
    print list03
    
    print "移除列表中的一个元素(默认最后一个元素),并且返回该元素的值"
    print list03.pop(0)
    print list03
    
    print "移除列表中某个值的第一个匹配项"
    list03.remove(1)
    print list03
    
    print "反向列表中元素"
    list03.reverse()
    print list03
    
    print "对原列表进行排序"
    list03.sort()
    print list03
    #结果
    [root@localhost 20170120]# python xulie.py 
    ['runoob', 786, 2.23, 'john', 70.200000000000003]
    [123, 'john']
    列表截取
    runoob
    70.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
    迭代
    runoob
    786
    2.23
    john
    70.2
    比较两个列表的元素
    1
    列表最大/最小值
    4
    0
    将元组转换为列表
    [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

  • 相关阅读:
    CentOS7安装iptables防火墙
    Linux下ntpdate时间同步
    linux下的时间及时区设置
    linux下的DNS
    sysctl
    ab -n -c
    VIM 中 查看{}是否闭合,按%跳转到下个闭合
    要删除共享的初始登陆名 cmd下输入net use * /delete
    case in esac ` for in do done ` while true / false
    read op case $op in
  • 原文地址:https://www.cnblogs.com/yycc/p/7058723.html
Copyright © 2011-2022 走看看