search
HomeBackend DevelopmentPython Tutorialpython列表与元组详解实例

在这章中引入了数据结构的概念。数据结构是通过某种方式组织在一起的数据元素的集合。在python中,最基本的数据结构就是序列。序列中的每个元素被分配一个序号,即元素的位置,也被称为索引。注意:第一个索引是0。
1.序列概览
python有6种内建的序列:列表,元组,字符串,Unicode字符串,buffer对象和xrange对象。
 这里重点介绍列表和元组。列表和元组主要区别在于,列表可以修改,元组不可修改。一般来说,在几乎所有情况下列表都可以代替元组。
在需要操作一组数值的时候,序列很好用:

复制代码 代码如下:

Edward = ["Gumby",42]

 同时,序列可以包含其他的序列。如:
复制代码 代码如下:

Edward = ["Gumby",42]
John = ["Smith",50]
database = [Edward,John]

2. 通用序列操作
所有序列类型都可以进行某些特点的操作,包括:索引,分片,加,乘以及检查某个元素是否属于序列的成员(成员资格)。除此之外,python还有计算序列长度,找出最大元素和最小元素的内建函数。
2.1 索引
序列中的所有元素都是有编号的--从0开始递增。这些元素可以通过编号分别访问:
复制代码 代码如下:

>>>greeting = "hello"
>>>greeting[0]
'H'

使用负数索引的话,python会从右边,也就是从最后一个元素开始计数,最后一个元素的位置编号是-1!
复制代码 代码如下:

>>> greeting[-1]
'g'

2.2 分片
分片可以访问一定范围内的元素,通过冒号相隔的2个索引来实现。分片对于提取序列的一部分是很有用的,第一个索引是提取部分的第一个元素编号,最后的索引是分片之后剩下部分的第一个元素编号。
复制代码 代码如下:

>>> number = [1,2,3,4,5,6,7,8,9,10]
>>> number[3:6]
[4,5,6]
>>> number[0:1]
[1]

2.2.1 优雅的捷径
需要访问最后3个元素,可以这样显式操作:
复制代码 代码如下:

>>> number[7:10]
[8,9,10]

这里索引10指向的第11个元素不存在,却是在最后一个元素之后。
如果需要从列表结尾开始计数,就是说如果分片所得部分包括序列结尾的元素,那么只需置空最后一个索引:
复制代码 代码如下:

>>> number[-3:]
[8,9,10]

这种方法适用于序列开始的元素或者显示整个序列:
复制代码 代码如下:

>>> number[:3]
[1,2,3]
>>> number[:]
[1,2,3,4,5,6,7,8,9,10]

2.2.2 更大的步长
进行分片的时候,分片的开始和结束都需要进行指定,另一个参数-步长,通常是隐式设置的。默认的步长是1。如果显示设置步长为比1大的数,那么会跳过某些元素。
复制代码 代码如下:

>>> number[0:10:2]
[1,3,5,7,9]
>>> number[3:6:3]
[4]

步长不能为0,但是可以是负数,即从右到左提取元素:
复制代码 代码如下:

>>> number[10:0:-2]
[10,8,6,4,2]
>>> number[0:10:-2]
[]

上面第二个式子是错误的,使用一个负数作为步长时,必须让开始点大于结束点。
2.3 序列相加
通过使用加号可以进行序列的连接操作:
复制代码 代码如下:

>>> [1,2,3] + [4,5,6]
[1,2,3,4,5,6]
>>>'hello, ' + 'world'
'hello, world'
>>>[1,2,3] + 'hello'
TypeError:can only concatenate list(not 'string') to list

如上面第三个例子所示,列表和字符串是无法连接到一块的,尽管它们都是序列,但是只有2种相同类型的序列才能进行连接操作。
复制代码 代码如下:

2.4 乘法
用数字x乘以一个序列会生成新的序列,在新的序列中,原来的序列被重复x次:
[code]
>>> 'python' *5
'pythonpythonpythonpythonpython'
>>> [42] * 5
[42,42,42,42,42]

None,空列表和初始化
空列表可以通过2个中括号进行表示([]),但是如果想创建一个占用十个元素空间,却不包括任何有用内容的列表,我们就需要一个值来代表空值,可以这样做:
复制代码 代码如下:

>>> sequence = [None] * 10
>>> sequence
[None,None,None,None,None,None,None,None,None,None]

2.5 成员资格
为了检查一个值是否在序列中,可以使用in运算符。它检查某个条件是否为真,然后返回相应的值(True或False)
复制代码 代码如下:

>>> p = 'write'
>>> 'w' in p
True
>>> user =["a","b","c"]
>>> raw_input('Enter:') in user
Enter:a
True

2.6 长度,最大最小值
复制代码 代码如下:

>>> numbers = [10,20,30]
>>> len(numbers)
>>> max(numbers)
>>> min(numbers)
>>> max(1,99)
>>> min(1,99)

上面最后2个例子中,max函数和min函数的参数并不是序列,而是以多个数字直接作为参数。
3.列表:python的“苦力”
3.1 list函数
因为字符串不能像列表一样被修改,所以有时候根据字符串创建列表会很有用。ps:list函数适用于所有类型的列表,不只是字符串。
复制代码 代码如下:

>>> list('hello')
['h','e','l','l','o']

提示:可以用下面的表达式将一个由字符组成的列表转换为字符串:
复制代码 代码如下:

>>> strs = ‘ '.jion(list)
>>> strs
"h e l l o"

3.2 基本列表操作
方法是一个与某些对象有紧密联系的函数,对象可能是列表,数字,也可能是字符串或者其他类型的对象。列表提供了几个方法,用于检测或者修改其中的内容。
 3.2.1 append
append方法用于在列表末尾追加新的对象:
复制代码 代码如下:

>>> lst = [1,2,3]
>>> lst.append(4)
>>> lst
[1,2,3,4]

注意:append方法不是简单地返回一个修改过的新列表,而是直接修改原来的列表。

3.2.2 count
count方法统计某个元素在列表中出现的次数:
复制代码 代码如下:

>>> x =[[1,2],1,1,[1,2,[1,2]]]
>>> x.count(1)
2

3.2.3 extend
extend方法可以在列表的末尾一次性追加另一个序列中的多个值。
注意:extend方法和连接操作(+)最主要的区别在于:extend方法修改了被扩展的序列,而连接操作会返回一个全新的列表。

3.2.4 index
index方法用于从列表中找出某个值第一次匹配项的索引位置:
复制代码 代码如下:

>>> knights = ['we','are','the','knights']
>>> knights.index('the')
2
>>> knights.index("hi")
ValueError:list.index(x):x not in list

当匹配项没有被找到时,会引发一个异常。

3.2.5 insert
insert方法用于将对象插入到列表中:
复制代码 代码如下:

>>> numbers = [1,2,3,6]
>>> numbers = insert(3,5)
>>> numbers
[1,2,3,5,6]
>>> numbers[3:3] = [4]
>>> numbers
[1,2,3,4,5,6]

上面最后一个例子中通过分片赋值实现插入,但是可读性不如insert。

3.2.6 pop
pop方法会移除列表中的一个元素,并且放回该元素的值,它是唯一一个既能修改列表又能返回元素值的列表方法:
复制代码 代码如下:

>>> x = [1,2,3]
>>> x.pop()
3
>>> x
[1,2]

3.2.7 remove
 remove方法用于移除列表中某个值的第一个匹配项:
复制代码 代码如下:

>>> x = ['to','be','to']
>>> x.remove('to')
>>> x
['be','to']
>>> x.remove('kkk')
ValueError:list.remove(x):x not in list

可以看到只有第一次出现的值被移除了,而不在列表中的值是不会移除的。

 3.2.8 reverse
reverse方法将列表中的元素反向存放:
复制代码 代码如下:

>>> x = [1,2,3]
>>> x.reverse()
>>> x
[3,2,1]

 3.2.9 sort
sort方法用于在原位置对列表进行排序,意味着改变原来的列表,而不是简单地返回一个已排序的列表副本。
如果想要得到一个排序而不改变原来的数值,那就需要先赋值再排序:
复制代码 代码如下:

>>> x = [4,2,7,1]
>>> y = x[:]
>>> y.sort()
>>> x
[4,2,7,1]
>>>y
[1,2,4,7]

注意:上面的例子中赋值使用的是y=x[:],分片是一种很有效率的复制整个列表的方法。如果简单地把x赋值给y是没有的(y=x),因为这样做就让x和y指向同一个列表了。
另一种获取已排序列表副本的方法是使用sorted函数:
复制代码 代码如下:

>>> x = [4,5,3,7,2]
>>> y = sorted(x)
>>> x
[4,5,3,7,2]
>>> y
[2,3,4,5,7]
 
 3.2.10 高级排序
如果希望元素能够按照特定的方式进行排序,那么可以通过compare(x,y)的形式自定义比较函数。内建cmp函数提供了比较函数的默认实现方式:
复制代码 代码如下:

>>> cmp(1,2)
-1
>>> cmp(2,1)
>>> cmp(1,1)
>>> numbers = [5,3,9,7]
>>> numbers.sort(cmp)
>>> numbers
[3,5,7,9]

sort方法有另外2个可选参数-key和reverse。要使用它们,那就要通过名字来指定。
复制代码 代码如下:

>>> x = ['a','abc','ab']
>>> x.sort(key=len)
>>> x
['a','ab','abc']
>>> y = [2,4,1,5]
>>> y.sort(reverse)
>>> y
[5,4,2,1]


 4.元组:不可变序列
 创建元组的语法很简单:如果你用逗号分隔了一些值,那么你就自动创建了元组。
复制代码 代码如下:

>>>1,2,3
(1,2,3)
>>>(1,2,3)
(1,2,3)
>>>()
()
>>>42,
(42,)

如上面最后一个例子,如果要实现一个包括一个值的元组,必须在数值后面加一个逗号。
4.1 tuple函数
tuple将一个序列作为参数并把它转换为元组,如果参数是元组,那么该参数就会被原样返回:
复制代码 代码如下:

>>> tuple([1,2,3])
(1,2,3)
>>> tuple('abc')
('a','b','c')
>>> tuple((1,2,3))
(1,2,3)

4.2 基本元组操作
元组其实并不复杂,除了创建元组和访问元组元素之外,也没有太多其他操作:
复制代码 代码如下:

>>>x = 1,2,3
>>>x[1]
2
>>> x[0:2]
(1,2)

元组的分片还是元组,就像列表的分片还是列表一样。

4.3 那么,意义何在
元组是不可替代的:
(1)元组可以在映射中当作键使用,而列表不行。
(2)元组作为很多内建函数和方法的返回值存在。

 

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
The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?Apr 02, 2025 am 07:09 AM

How to solve the problem of Jieba word segmentation in scenic spot comment analysis? When we are conducting scenic spot comments and analysis, we often use the jieba word segmentation tool to process the text...

How to use regular expression to match the first closed tag and stop?How to use regular expression to match the first closed tag and stop?Apr 02, 2025 am 07:06 AM

How to use regular expression to match the first closed tag and stop? When dealing with HTML or other markup languages, regular expressions are often required to...

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),