Home Backend Development Python Tutorial What are the python sequence types?

What are the python sequence types?

Jun 17, 2019 am 11:58 AM
python

What are the sequence types in python? What is a sequence type in Python? Learn more about it in this article.

What are the python sequence types?

Sequence: character, list, tuple

All sequences support iteration

Sequence Represents an ordered collection of objects whose index is a non-negative integer

Characters and tuples belong to immutable sequences, and lists are mutable

1)Characters

String literal: Put the text in single quotes, double quotes or triple quotes;

    '    ''    '''
        >>> str1 = ' hello, fanison '
        >>> type(str1)
        str
Copy after login

If you want to use unicode encoding, use the character u before the character to identify it

        >>> str2 = u'你好,fanison'
        >>> type(str2)
        unicode
Copy after login

Documentation string: If the first statement of a module, class or function is one character, the string becomes the documentation string and can be referenced using the __doc__ attribute;

Example:

            >>> def printName():
                    "the function is print hello"
                    print 'hello'
            >>> printName.__doc__
Copy after login

operator:

# S [i] Return to a sequence element I

slicing computing s [i: j] Return to one Slicing

Extended slicing operator s[i:j:stride]

Example:

            >>> 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处到开始处倒着取
Copy after login

Note:

Step If it is positive, it means that the index is taken from small to large i < j

The step path is negative, it means that it is taken backward, and the index is from large to small i > j

Supported Operations:

Indexing, slicing, min(), max(), len(), etc.

       

len(s)               The number of elements in s

min (s) s minimum value

Max (s) s) The maximum value of

## Support method:

S.index (SUB [,start [,end]])           Find the position where the specified string sub first appears

S.upper()                                     Convert a string to uppercase form

S.lower()                                                              one String into a lowercase form

# S.Join (T) uses S as a string in the separatist connection sequence T

 >>> l1 = list(str1)
>>> l1
[&#39;h&#39;, &#39;e&#39;, &#39;l&#39;, &#39;l&#39;, &#39;o&#39;, &#39;,&#39;, &#39;f&#39;, &#39;a&#39;, &#39;n&#39;, &#39;i&#39;, &#39;s&#39;, &#39;o&#39;, &#39;n&#39;]
>>> &#39;&#39;.join(l1)
&#39;hello,fanison&#39;             使用空字符作为分隔符连接列表l1
S.replace(old, new[, count])             替换一个字符串
>>> str1.replace(&#39;fan&#39;,&#39;FAN&#39;)
&#39;hello,FANison&#39;
Copy after login

Note:

## Use help () to get Its help

>>> help(str.join)

           

2) List

List: Container Type

                                                                                                                                                                                                            . Modify

to modify the specified index element, modify the specified shard, delete the statement, the built -in method

##

         >>> list1 = [ 1,2,3,&#39;x&#39;,&#39;n&#39; ]
         >>> list1[1]=56
         >>> print list1
         [1, 56, 3, &#39;x&#39;, &#39;n&#39;]
         >>> list1[1:3]=[]              会删除索引1到索引3之前的元素
         >>> print list1
         [1, &#39;x&#39;, &#39;n&#39;]   
         >>> del(list1[1])              使用del函数删除list索引为1的元素
         >>> print list1
         [1, &#39;n&#39;]
Copy after login

Note:

## Because support the original modification of the original place , Will not change the memory location, you can use ID () to view its location change

Built

##               L.append(object)               Append a new element to the end of L                                                                           ’s . Add a merged list (the contents of the second list will be appended to the end as a single element)

      >>> l1 = [ 1,2,3 ]
                        >>> l2 = [ &#39;x&#39;,&#39;y&#39;,&#39;z&#39;]
                        >>> l1.append(l2)
                        >>> l1
                        [1, 2, 3, [&#39;x&#39;, &#39;y&#39;, &#39;z&#39;]]          使用append方法会以其原有存在形式追加
                        >>> l1 = [ 1,2,3 ]
                        >>> l1.extend(l2)
                        >>> l1
                        [1, 2, 3, &#39;x&#39;, &#39;y&#39;, &#39;z&#39;]            注意两种增加的区别
Copy after login

L.pop ([Index]) Return the element index and remove it from the list. The element that is key

                        >>> l1 = [ &#39;x&#39;,2,&#39;abc&#39;,16,75 ]
                        >>> l1.pop(2)                       pop方法是按索引移除
                        &#39;abc&#39;
                        >>> l1
                        [&#39;x&#39;, 2, 16, 75]
                        >>> l1.remove(16)                   remove方法是按值移除
                        >>> l1
                        [&#39;x&#39;, 2, 75]
Copy after login

                                                                                                                                                        to ’ s ’ s ’ s ’ s to ’ t               ’ ’ ’ ’ s ‐ to ‐ ‐ ‐‐ ‐‐ ‐‐n-key, ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​  

L.insert(index, object) 在索引index处插入值

                        >>> l1.insert(1,&#39;abc&#39;)
                        >>> l1
                        [&#39;x&#39;, &#39;abc&#39;, 2, 75]
Copy after login

L.sort() 排序

L.reverse() 逆序

                        >>> l1.sort()
                        [2, 75, &#39;abc&#39;, &#39;x&#39;]
                        >>> l1.reverse()
                        [&#39;x&#39;, &#39;abc&#39;, 75, 2]
Copy after login

l1 + l2: 合并两个列表,返回一个新的列表;不会修改原列表;

                        >>> l1 = [ 1,2,3]
                        >>> l2 = [ &#39;x&#39;,&#39;y&#39;,&#39;z&#39;]
                        >>> l1 + l2
                        [1, 2, 3, &#39;x&#39;, &#39;y&#39;, &#39;z&#39;]
Copy after login

l1 * N: 把l1重复N次,返回一个新列表;

                        >>> l1 * 3
                        [1, 2, 3, 1, 2, 3, 1, 2, 3]         使用id()查看是否生成新列表
Copy after login

成员关系判断字符:

in 用法: item in container

not in item not in container

                            >>> l1 = [ &#39;x&#39;,&#39;y&#39;,3 ]
                            >>> &#39;y&#39; in l1
                            True
                            >>> &#39;x&#39; not in l1
                            False
Copy after login

列表解析:[]

列表复制方式:

浅复制:两者指向同一内存对象

                    >>> l1 = [ 1,2,3,4 ]
                    >>> l2 = l1
                    >>> id(l1) == id(l1)
                    True                            可以看出两者内存地址相同
                    >>> l1.append(&#39;x&#39;)
                    >>> print l1
                    [ 1,2,3,4,&#39;x&#39; ]
                    >>> print l2
                     [ 1,2,3,4,&#39;x&#39; ]
Copy after login

深复制:两者指向不同内存对象

1)导入copy模块,使用deepcoop方法

                     >>> import copy
                     >>> l3 = copy.deepcopy(l1)
                     >>> id(l3) == id(l1)
                     False                          地址不同
Copy after login

2)复制列表的所有元素,生成一个新列表

                    >>> l4 = l1[:]              
                    >>> print l4
                    [ 1,2,3,4,&#39;x&#39; ]
                    >>> l1.append(6)
                    >>> print l1
                    [ 1,2,3,4,&#39;x&#39;,6 ]               l1改变
                    >>> print l4
                    [ 1,2,3,4,&#39;x&#39; ]                 l4不变
Copy after login

3)元组

表达式符号:()

容器类型

任意对象的有序集合,通过索引访问其中的元素,不可变对象,长度固定,异构,嵌套

常见操作:

                    >>> t1 = ( 1,2,3,&#39;xyz&#39;,&#39;abc&#39;)
                    >>> type(t1)
                    tuple
                    >>> len(t1)
                    5
                    >>> t2 = ()                             定义一个空元组
                    >>> t3 = ( , )
                    SyntaxError: invalid syntax             报错:使用逗号分隔的条件是最少要有一个元素
Copy after login

(1,)

                    >>> t1[:]
                    ( 1,2,3,&#39;xyz&#39;,&#39;abc&#39; )
                    >>> t1[1:]
                    (2, 3, &#39;xyz&#39;, &#39;abc&#39;)
Copy after login

(1,2)

                    >>> t1[1:4]
                    (2, 3, &#39;xyz&#39;)
                    >>> t4 = &#39;x&#39;,1,&#39;yz&#39;,45,[2,4,6]              注意!!!这样也可以生成元组
                    >>> t4  
                    (&#39;x&#39;, 1, &#39;yz&#39;, 45, [2, 4, 6])
Copy after login

t1 + t4: 合并两个元组,返回一个新的元组;不会修改原元组;

                    >>> t1 + t4
                    (1, 2, 3, &#39;xyz&#39;, &#39;abc&#39;, &#39;x&#39;, 1, &#39;yz&#39;, 45, [2, 4, 6])
Copy after login

t1 * N: 把l1重复N次,返回一个新元组;

                    >>> t1 * 3
                    (1, 2, 3, &#39;xyz&#39;, &#39;abc&#39;, 1, 2, 3, &#39;xyz&#39;, &#39;abc&#39;, 1, 2, 3, &#39;xyz&#39;, &#39;abc&#39;)
Copy after login

成员关系判断

in

not in

注意:

虽然元组本身不可变,但如果元组内嵌套了可变类型的元素,那么此类元素的修改不会返回新元组;

例:

                    >>> t4 = (&#39;x&#39;, 1, &#39;yz&#39;, 45, [2, 4, 6])
                    >>> id(t4)
                    44058448
                    >>> t4[4]                           
                    [2, 4, 6]
                    >>> t4[4].pop()                     弹出列表内一个元素
                    6
                    >>> print t4[4]
                    [2, 4]
                    >>> print t4
                    (&#39;x&#39;, 1, &#39;yz&#39;, 45, [2, 4]) 
                    >>> id(t4)
                    44058448                            由此可见,对元组内列表内的修改也会使元组发生改变,没有返回新元组
Copy after login

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 of this Website
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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

How is the GPU support for PyTorch on CentOS How is the GPU support for PyTorch on CentOS Apr 14, 2025 pm 06:48 PM

Enable PyTorch GPU acceleration on CentOS system requires the installation of CUDA, cuDNN and GPU versions of PyTorch. The following steps will guide you through the process: CUDA and cuDNN installation determine CUDA version compatibility: Use the nvidia-smi command to view the CUDA version supported by your NVIDIA graphics card. For example, your MX450 graphics card may support CUDA11.1 or higher. Download and install CUDAToolkit: Visit the official website of NVIDIACUDAToolkit and download and install the corresponding version according to the highest CUDA version supported by your graphics card. Install cuDNN library:

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

MiniOpen Centos compatibility MiniOpen Centos compatibility Apr 14, 2025 pm 05:45 PM

MinIO Object Storage: High-performance deployment under CentOS system MinIO is a high-performance, distributed object storage system developed based on the Go language, compatible with AmazonS3. It supports a variety of client languages, including Java, Python, JavaScript, and Go. This article will briefly introduce the installation and compatibility of MinIO on CentOS systems. CentOS version compatibility MinIO has been verified on multiple CentOS versions, including but not limited to: CentOS7.9: Provides a complete installation guide covering cluster configuration, environment preparation, configuration file settings, disk partitioning, and MinI

How to operate distributed training of PyTorch on CentOS How to operate distributed training of PyTorch on CentOS Apr 14, 2025 pm 06:36 PM

PyTorch distributed training on CentOS system requires the following steps: PyTorch installation: The premise is that Python and pip are installed in CentOS system. Depending on your CUDA version, get the appropriate installation command from the PyTorch official website. For CPU-only training, you can use the following command: pipinstalltorchtorchvisiontorchaudio If you need GPU support, make sure that the corresponding version of CUDA and cuDNN are installed and use the corresponding PyTorch version for installation. Distributed environment configuration: Distributed training usually requires multiple machines or single-machine multiple GPUs. Place

How to choose the PyTorch version on CentOS How to choose the PyTorch version on CentOS Apr 14, 2025 pm 06:51 PM

When installing PyTorch on CentOS system, you need to carefully select the appropriate version and consider the following key factors: 1. System environment compatibility: Operating system: It is recommended to use CentOS7 or higher. CUDA and cuDNN:PyTorch version and CUDA version are closely related. For example, PyTorch1.9.0 requires CUDA11.1, while PyTorch2.0.1 requires CUDA11.3. The cuDNN version must also match the CUDA version. Before selecting the PyTorch version, be sure to confirm that compatible CUDA and cuDNN versions have been installed. Python version: PyTorch official branch

How to install nginx in centos How to install nginx in centos Apr 14, 2025 pm 08:06 PM

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.

See all articles