Home Backend Development Python Tutorial Python中列表和元组的相关语句和方法讲解

Python中列表和元组的相关语句和方法讲解

Jun 10, 2016 pm 03:07 PM
python tuple list

列表(list):

首先,列表属于序列,那么序列类型可用如下内建函数——
list(iter):把可迭代对象转换为列表。
str(obj):把obj对象转换为字符串,即用字符串来表示这个对象。
tuple(iter):把一个可迭代对象转换为一个元组。
unicode(obj):把对象转换成Unicode字符串。
basestring():抽象工厂函数,其作用仅仅是为str和unicode函数提供父类,所以不能被实例化,也不能被调用。
enumerate(iter):接受一个可迭代对象作为参数,返回一个enumerate对象,该对象生成由iter每个元素的index值和item值组成的元组。
len(seq):返回seq的长度。
max(iter,key=None)、max(arg0,arg1...,key=None):返回iter或(arg0,arg1...)的最大值,如果指定了key,这个key必须是一个可以传给sort()方法的,用于比较的回调函数。
min(iter,key=None)、min(arg0,arg1...,key=None):返回iter或(arg0,arg1...)的最小值,如果指定了key,这个key必须是一个可以传给sort()方法的,用于比较的回调函数。
reversed(seq):接受一个序列作为参数,返回一个以逆序访问的迭代器。
sorted(iter,cmp=None,key=None,reverse=False):接受一个可迭代对象作为参数,返回一个有序的列表,可选参数cmp、key和reverse和list.sort()内建函数含义一样。
sum(seq,init=0):返回seq和可选参数init的总和,其效果等同于reduce(operator.add,seq,init)。
zip([it0,it1...]):返回一个列表,其第一个元素是it0、it1...这些元素的第一个元素组成的一个元组,其它元素依次类推。

列表就像一个线性容器,但是比C++的 lis t扩展多得多
列表里的元素可以是相同类型,也可以包含各种类型,比如列表里嵌套另一个列表

列表示例:

>>> L1 = [1,2,3] 
>>> type(L1) 
<class 'list'> 
>>> L1 = [1,'a',2,1.4] 
>>> L1 
[1, 'a', 2, 1.4] 
>>> L1 = [ ['sub'],1,'n'] 
>>> L1 
[['sub'], 1, 'n'] 

Copy after login

list的索引是也是从0开始,但也可以从后访问,L1[-1] 表示L1中的最后一个元素

>>> L1 
[['sub'], 1, 'n'] 
>>> L1[0] 
['sub'] 
>>> L1[-1] 
'n' 

Copy after login

对列表可以进行切片,切片的操作类似于对函数的调用,返回值一个新的列表
切片 L1[ x : y : z ] 是半开闭区间(z通常不用写),如L1[1:3] 返回的是一个从 L1[1] 开始到 L1[2] 结束的列表,不包含L1[3]
x 不写表示从头开始,y 不写表示直到列表结束,z 用于表示步长, 默认是1, 可以认为是在这个区间里每 z 个元素取一个(取第一个),可以是负数,表示从后到前遍历

>>> L1 = [1,2,3,4,5,6] 
>>> L1[1:3] 
[2, 3] 
>>> L1[:3] 
[1, 2, 3] 
>>> L1[1:] 
[2, 3, 4, 5, 6] 
>>> L1[-3:-1] 
[4, 5] 
>>> L2 = L1[:] 
>>> L2 
[1, 2, 3, 4, 5, 6] 
>>> L1[::2] 
[1, 3, 5] 
>>> L1[::-1] 
[6, 5, 4, 3, 2, 1] 

Copy after login

列表可以做加法,做乘法,字符串也可以看做一个字符的列表

>>> L1 = [1,2] 
>>> L2 = [3,4] 
>>> L1 + L2 
[1, 2, 3, 4] 
>>> 5 * L1 
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2] 

Copy after login

in语句,判断一个对象是否在一个字符串/列表/元组里
not 语句表示对后面的否定
len 可以检测字符串/列表/元祖/字典的元素个数
max 可以返回最大元素,min 返回最小元素

>>> L1 
[1, 2, 3, 4, 2] 
>>> 3 in L1 
True 
>>> 5 in L1 
False 
>>> 3 not in L1 
False 
>>> 5 not in L1 
True 
>>> len(L1) 
5 
>>> max(L1) 
4 
>>> min(L1) 
1 

Copy after login

操作:

>>> #赋值 
>>> L1[1] = 5 
>>> L1 
[1, 5, 3, 4, 2] 
>>> #删除 
>>> del L1[1] 
>>> L1 
[1, 3, 4, 2] 
>>> #分片赋值 
>>> L1[2:] = [6,7,8] 
>>> L1 
[1, 3, 6, 7, 8] 
>>> L1[1:3] = [] 
>>> L1 
[1, 7, 8] 

Copy after login

list 的函数:
append( x ) 是将 x 作为一个元素添加到列表的末尾,即使 x 是一个列表

>>> L1 
[1, 2, 7, 8] 
>>> L1.append(3) 
>>> L1 
[1, 2, 7, 8, 3] 
>>> L1.append([4,5]) 
>>> L1 
[1, 2, 7, 8, 3, [4, 5]] 
>>> 4 in L1 
False 

Copy after login


count( x) 统计 x 在列表中出现的次数

>>> L1 = [1, 2, 7, 8] 
>>> L1.count(2) 
1 
>>> L1.count(3) 
0 

Copy after login


extend( x ) 将x 作为一个列表与原列表合并,添加到末尾。若不是列表,则编译器尝试将 x 转换为列表然后执行操作,不成功就会报错

>>> L1 
[1, 2, 7, 8] 
>>> L1.extend([4,5]) 
>>> L1 
[1, 2, 7, 8, 4, 5] 
>>> 4 in L1 
True 

Copy after login


index ( x ) 返回 x 在列表中的坐标,若 x 不在列表中会出错

>>> L1.index(2) 
1 

Copy after login

insert( i , x) 在位置i 插入元素x

>>> L1 
[1, 2, 7, 8, 4, 5] 
>>> L1.insert(0,'a') 
>>> L1 
['a', 1, 2, 7, 8, 4, 5] 
>>> L1.insert(-1,'b') 
>>> L1 
['a', 1, 2, 7, 8, 4, 'b', 5] 

Copy after login

pop( i ) 删除位置 i 的元素并将它返回,默认可以不写 i ,删除最后一个元素,不存在会出错

>>> L1 = [1, 2, 7, 8] 
>>> L1.pop(1) 
2 
>>> L1 
[1, 7, 8] 
>>> L1.pop() 
8 
>>> L1 
[1, 7] 

Copy after login

remove( x ) 移除在 列表中 x 的第一个匹配项,x 不存在会出错

>>> L1.remove(2) 
>>> L1 
[1, 7, 8] 

Copy after login


reverse() 将列表逆序

>>> L1 = [1, 2, 7, 8] 
>>> L1.reverse() 
>>> L1 
[8, 7, 2, 1] 

Copy after login


sort 将原列表排序,返回None,有两个可选参数,key 和 reverse,默认为升序排列

>>> L1 
[8, 7, 2, 1] 
>>> L1.sort() 
>>> L1 
[1, 2, 7, 8] 
>>> L1.sort(reverse = True) 
>>> L1 
[8, 7, 2, 1] 


>>> L1 = ['a','ccc','abcd','bc','cd','abc'] 
>>> L1.sort(key = len) 
>>> L1 
['a', 'bc', 'cd', 'ccc', 'abc', 'abcd'] 

Copy after login

元组(tuple)
元组也属于序列,但元组为不可修改的列表。所以元组没有以上序列通用方法可用!
一个元素的元组表示为 ( 1 , )

>>> x = (1,) 
>>> type(x) 
<class 'tuple'> 
>>> x = (1) 
>>> type(x) 
<class 'int'> 

Copy after login

元组可转换成列表,反之亦然。
内建的 tuple() 函数接受一个列表参数,并返回一个包含同样元素的元组,而 list() 函数接受一个元组参数并返回一个列表。
从效果上看, tuple() 冻结列表,而 list() 融化元组。

>>> x = [1,2,4,3,1] 
>>> y = (1,2,4,3,1) 
>>> type(x) 
<class 'list'> 
>>> type(y) 
<class 'tuple'> 
>>> z = tuple(x) 
>>> z 
(1, 2, 4, 3, 1) 
>>> z = list(y) 
>>> z 
[1, 2, 4, 3, 1] 

Copy after login

可以用列表 或 元组 进行一次多赋值:

>>> L1 = (1,2,4) 
>>> (x, y, z) = L1 
>>> x 
1 
>>> y 
2 
>>> z 
4 

>>> L1 = [1,2,4] 
>>> (x,y,z) = L1 
>>> x 
1 
>>> y 
2 
>>> z 
4 

Copy after login


[] ,和 () 在布尔值中表示 False

 

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

See all articles