search
HomeBackend DevelopmentPython TutorialWhat are the Python sequence types?
What are the Python sequence types?Jul 20, 2017 pm 03:31 PM
pythonsequencetype

Python sequence type

序列:字符、列表、元组

    所有序列都支持迭代
    序列表示索引为非负整数的有序对象集合
    字符和元组属于不可变序列,列表可变

1)Character

    字符串字面量:把文本放入单引号、双引号或三引号中;
    '    ''    '''
        >>> str1 = ' hello, fanison '
        >>> type(str1)
        str
    
    如果要使用unicode编码,则在字符之前使用字符u进行标识
        >>> str2 = u'你好,fanison'
        >>> type(str2)
        unicode
        
    文档字串:模块、类或函数的第一条语句是一个字符的话,该 字符串就成为文档字符串,可以使用__doc__属性引用;
        例:
            >>> def printName():
                    "the function is print hello"
                    print 'hello'
            >>> printName.__doc__
            
    运算符:
        索引运算符          s[i]        返回一个序列的元素i
        切片运算符          s[i:j]      返回一个切片
        扩展切片运算符      s[i:j:stride]
      
        例:
            >>> str3 = 'hello,fanison'
            >>> str2[0:]
            'hello,fanison'      返回所有元素
            >>> str2[0:7]
            'hello,f'            返回索引7之前的所有元素
            >>> str2[0:7:2]
            'hlof'               返回从索引0到6内步径为2的元素,即隔一个取一个
            >>> str2[7:0:-2]        
            'a,le'               从索引7处倒着隔一个取一个取到索引1处
            >>> str2[-4:-1]
            'iso'                从索引-4处取到-2处       
            >>> str2[-4::-1]
            'inaf,olleh'         从-4处到开始处倒着取
        注意:
            步径为正表示  正着取,索引从小到大          i  j
        
    支持运算:
        索引、切片、min()、max()、len()等
        
            len(s)              s中的元素个数
            min(s)              s的最小值
            max(s)              s的最大值
            
   支持方法:
        S.index(sub [,start [,end]])            找到指定字符串sub首次出现的位置
        S.upper()                               将一个字符串转换为大写形式
        S.lower()                               将一个字符串转化为小写形式
        S.join(t)                               使用s作为分隔符连接序列t中的字符串
                    >>> l1 = list(str1)
                    >>> l1
                    ['h', 'e', 'l', 'l', 'o', ',', 'f', 'a', 'n', 'i', 's', 'o', 'n']
                    >>> ''.join(l1)
                    'hello,fanison'             使用空字符作为分隔符连接列表l1
       S.replace(old, new[, count])             替换一个字符串
                    >>> str1.replace('fan','FAN')
                    'hello,FANison'
    注意:
        使用 help()获取其帮助
                >>> help(str.join)

2)List

列表:容器类型
         任意对象的有序集合,通过索引访问其中的元素,可变对象,长度可变,异构,任意嵌套
     
      支持在原处修改
            修改指定的索引元素,修改指定的分片,删除语句,内置方法
            
         >>> list1 = [ 1,2,3,'x','n' ]
         >>> list1[1]=56
         >>> print list1
         [1, 56, 3, 'x', 'n']
         >>> list1[1:3]=[]              会删除索引1到索引3之前的元素
         >>> print list1
         [1, 'x', 'n']   
         >>> del(list1[1])              使用del函数删除list索引为1的元素
         >>> print list1
         [1, 'n']
            注意:
                 因为支持原处修改,不会改变内存位置,可使用  id() 查看其位置变化
       
       内置方法:
                 L.count(value)                     计算value值出现的次数
                 L.append(object)                   将一个新元素追加到L末端                    
                 L.extend(iterable)                 增加合并列表(第二个列表内容会以单个元素追加至末端)
                        >>> l1 = [ 1,2,3 ]
                        >>> l2 = [ 'x','y','z']
                        >>> l1.append(l2)
                        >>> l1
                        [1, 2, 3, ['x', 'y', 'z']]          使用append方法会以其原有存在形式追加
                        >>> l1 = [ 1,2,3 ]
                        >>> l1.extend(l2)
                        >>> l1
                        [1, 2, 3, 'x', 'y', 'z']            注意两种增加的区别
                L.pop([index])                      返回元素index并从列表中移除它,如果省略则返回并移除列表最后一个元素
                L.remove(key)                       移除值为key的元素
                        >>> l1 = [ 'x',2,'abc',16,75 ]
                        >>> l1.pop(2)                       pop方法是按索引移除
                        'abc'
                        >>> l1
                        ['x', 2, 16, 75]
                        >>> l1.remove(16)                   remove方法是按值移除
                        >>> l1
                        ['x', 2, 75]  
                L.index(value)                        指定值首次出现的位置
                L.insert(index, object)               在索引index处插入值
                        >>> l1.insert(1,'abc')
                        >>> l1
                        ['x', 'abc', 2, 75]
                L.sort()                              排序
                L.reverse()                           逆序
                        >>> l1.sort()
                        [2, 75, 'abc', 'x']
                        >>> l1.reverse()
                        ['x', 'abc', 75, 2]
                        
        l1 + l2: 合并两个列表,返回一个新的列表;不会修改原列表;
                        >>> l1 = [ 1,2,3]
                        >>> l2 = [ 'x','y','z']
                        >>> l1 + l2
                        [1, 2, 3, 'x', 'y', 'z']
                        
        l1 * N: 把l1重复N次,返回一个新列表; 
                        >>> l1 * 3
                        [1, 2, 3, 1, 2, 3, 1, 2, 3]         使用id()查看是否生成新列表
        
        成员关系判断字符:  
                        in              用法:   item in container
                        not in               item not in container
                            >>> l1 = [ 'x','y',3 ]
                            >>> 'y' in l1
                            True
                            >>> 'x' not in l1
                            False
                            
       列表解析:[]
       
       列表复制方式:
            浅复制:两者指向同一内存对象
                    >>> l1 = [ 1,2,3,4 ]
                    >>> l2 = l1
                    >>> id(l1) == id(l1)
                    True                            可以看出两者内存地址相同
                    >>> l1.append('x')
                    >>> print l1
                    [ 1,2,3,4,'x' ]
                    >>> print l2
                     [ 1,2,3,4,'x' ]
            深复制:两者指向不同内存对象
                    1)导入copy模块,使用deepcoop方法
                     >>> import copy
                     >>> l3 = copy.deepcopy(l1)
                     >>> id(l3) == id(l1)
                     False                          地址不同
                     
                    2)复制列表的所有元素,生成一个新列表
                    >>> l4 = l1[:]              
                    >>> print l4
                    [ 1,2,3,4,'x' ]
                    >>> l1.append(6)
                    >>> print l1
                    [ 1,2,3,4,'x',6 ]               l1改变
                    >>> print l4
                    [ 1,2,3,4,'x' ]                 l4不变

3)Tuple

    表达式符号:()

    容器类型
        任意对象的有序集合,通过索引访问其中的元素,不可变对象,长度固定,异构,嵌套
    
    常见操作:
        ()                      
                    >>> t1 = ( 1,2,3,'xyz','abc')
                    >>> type(t1)
                    tuple
                    >>> len(t1)
                    5
                    >>> t2 = ()                             定义一个空元组
                    >>> t3 = ( , )
                    SyntaxError: invalid syntax             报错:使用逗号分隔的条件是最少要有一个元素
        
        (1,)
                    >>> t1[:]
                    ( 1,2,3,'xyz','abc' )
                    >>> t1[1:]
                    (2, 3, 'xyz', 'abc')
    
        (1,2)       
                    >>> t1[1:4]
                    (2, 3, 'xyz')
                    >>> t4 = 'x',1,'yz',45,[2,4,6]              注意!!!这样也可以生成元组
                    >>> t4  
                    ('x', 1, 'yz', 45, [2, 4, 6])

        t1 + t4: 合并两个元组,返回一个新的元组;不会修改原元组;
                    >>> t1 + t4
                    (1, 2, 3, 'xyz', 'abc', 'x', 1, 'yz', 45, [2, 4, 6])
        
       
       t1 * N:  把l1重复N次,返回一个新元组; 
                    >>> t1 * 3
                    (1, 2, 3, 'xyz', 'abc', 1, 2, 3, 'xyz', 'abc', 1, 2, 3, 'xyz', 'abc')

        成员关系判断
                in
                not in
     
        注意:
            虽然元组本身不可变,但如果元组内嵌套了可变类型的元素,那么此类元素的修改不会返回新元组;
                例:
                    >>> t4 = ('x', 1, 'yz', 45, [2, 4, 6])
                    >>> id(t4)
                    44058448
                    >>> t4[4]                           
                    [2, 4, 6]
                    >>> t4[4].pop()                     弹出列表内一个元素
                    6
                    >>> print t4[4]
                    [2, 4]
                    >>> print t4
                    ('x', 1, 'yz', 45, [2, 4]) 
                    >>> id(t4)
                    44058448                            由此可见,对元组内列表内的修改也会使元组发生改变,没有返回新元组

4)Sequence operation summary

What are the Python sequence types?

The above is the detailed content of What are the Python sequence types?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft