Python基础(3)--列表和元组

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

Python包含6种内建序列:列表、元组、字符串、Unicode字符串、buffer对象、xrange对象

本篇主要讨论最常用的两种类型:列表、元组

本文地址:http://www.cnblogs.com/archimedes/p/python-list-tuple.html,转载请注明源地址。

列表和元组的主要区别在于,列表可以修改,元组则不能。一般情况下,在几乎所有的情况下列表都可以代替元组

例如:使用序列可以表示数据库中一个人的信息(姓名,年龄)

>>> edward=['Edward Gumby',42]

序列还可以包含其他序列

>>> edward=['Edward Gumby',42]>>> john=['John Smith',50]>>> database=[edward,john]>>>database

[['Edward Gumby', 42], ['John Smith', 50]]

通用序列操作所有的序列操作都可以进行某些特定的操作。这些操作包括:索引、分片、加、乘以及检查某个元素是否属于序列的成员

索引

序列中的所有元素都是有编号的--从0开始递增。这些元素可以通过编号分别访问,如下:

>>> greeting='hello'>>>greeting[0]'h'>>> greeting[-1]'o'>>>'hello'[1]'e'

如果一个函数调用返回一个序列,那么可以直接对返回结果进行索引操作,例如:

>>> fourth=raw_input('Year:')[3]

Year:2005

>>>fourth'5'

#根据给定的年月日以数字形式打印出日期months=['January','February','March','APRil','May','June','July','August','September','October','November','December']#以1~31的数字作为结尾的列表endings=['st','nd','rd']+17*['th']\+['st','nd','rd']+7*['th']\+['st']

year=raw_input('Year:')

month=raw_input('Month(1-12):')

day=raw_input('Day(1-31):')

month_number=int(month)

day_number=int(day)#记得要将月份和天数减1,以获得正确的索引month_name=months[month_number-1]

ordinal=day+endings[day_number-1]printmonth_name+''+ordinal+','+year

View Code

运行结果:

>>>Year:1974Month(1-12): 8Day(1-31): 16August 16th,1974

分片

使用分片操作来访问一定范围内的元素,分片通过冒号相隔的两个索引来实现:

>>> tag='<a herf="http://www.python.org">Python web site</a>'>>> tag[9:30]'http://www.python.org'>>> tag[32:-4]'Python web site'

第一个索引是需要提取部分的第一个元素的编号,而最后的索引则是分片之后剩下部分的第一个元素的编号

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

[4, 5, 6]>>> numbers[0:1]

[1]

1、优雅的捷径

访问最后的三个元素,当然可以进行显示的操作

>>> numbers[7:10]

[8, 9, 10]>>> numbers[-3:-1]

[8, 9]>>> numbers[-3:0]

[]>>> numbers[-3:]

[8, 9, 10]

只有最后一个分片完成任务,这种方法同样适用序列开始的元素:

>>> numbers[:3]

[1, 2, 3]

实际上,如果需要复制整个序列,可以将两个索引都置空:

>>>numbers[:]

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

2、更大的步长

分片还有第三个参数--步长,通常都是隐式设置的,在一般情况下,步长是1,不能为0,但是可以为负数,即从右往左提取元素

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

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

[1, 3, 5, 7, 9]>>> numbers[3:6:3]

[4]>>> numbers[::4]

[1, 5, 9]>>> numbers[8:3:-1]

[9, 8, 7, 6, 5]>>> numbers[10:0:-2]

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

[]>>> numbers[::-2]

[10, 8, 6, 4, 2]>>> numbers[5::-2]

[6, 4, 2]>>> numbers[:5:-2]

[10, 8]

测试代码

序列相加

通过使用加号可以进行序列的连接操作:

>>> [1,2,3]+[4,5,6]

[1, 2, 3, 4, 5, 6]>>>'hello.'+'world!''hello.world!'>>> [1,2,3]+'world!'Traceback (most recent call last):

File "<pyshell#107>", line 1, in <module>

[1,2,3]+'world!'

TypeError: can only concatenate list (not "str") to list

乘法

用数字x乘以一个序列会生成新的序列,而在新的序列中,原来的序列将被重复x次

>>>'python'*5'pythonpythonpythonpythonpython'>>> [42]*10[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]

成员资格

为了检查一个值是否在序列中,可以使用in运算符,该运算符返回布尔值

>>> permissions='rw'>>>'w'inpermissions

True>>>'x'inpermissions

False

Enter your name: mlh

True>>> subject='$$$ Get rich now!!! $$$'>>>'$$$'insubject

True

长度、最小值和最大值

内建函数len、min、max,len函数返回序列中所包含元素的数量,min和max函数分别返回序列中最大和最小的元素

>>> numbers=[100,34,678]>>>len(numbers)3

>>>max(numbers)678

>>>min(numbers)34

>>> max(2,3)3

>>> min(9,3,2,5)2

list函数

list函数可以根据字符串创建列表

>>> list('hello')

['h','e','l','l','o']

基本列表操作:1、改变列表:元素赋值

使用索引标记来为某个特定的、位置明确的元素赋值:

>>> x=[1,1,1]>>> x[1]=2

>>>x

[1, 2, 1]

2、删除元素

使用del语句来实现:

>>> names=['Alice','Beth','Ceil','Dee-Dee','Earl']>>>delnames[2]>>>names

['Alice','Beth','Dee-Dee','Earl']

注意:Cecil是彻底删除,列表长度也从5变为4

3、分片赋值

>>>names

['p','e','r','l']>>> names[2:]

['r','l']>>> name=list('perl')>>>name

['p','e','r','l']>>> name[2:]=list('ar')>>>name

['p','e','a','r']>>> name[1:]=list('ython')>>>name

['p','y','t','h','o','n']>>> numbers=[1,5]>>> numbers[1:1]=[2,3,4]>>>numbers

[1, 2, 3, 4, 5]>>> numbers[1:4]=[]>>>numbers

[1, 5]

View Code

列表方法:

方法是一个与某些对象有紧密联系的函数,对象可能是列表、数字,也可能是字符串或者其他类型的对象,方法的调用方式:对象.方法(参数)

1、append

append方法用于在列表末尾追加新的对象:

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

[1, 2, 3, 4]

2、cout

count方法用于统计某个元素在列表中出现的次数:

>>> ['to','be','or','not','to','be'].count('to')2

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

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

3、extend

extend方法可以在列表的末尾一次性的追加另一个序列中的多个值

>>> a=[1,2,3]>>> b=[4,5,6]>>>a.extend(b)>>>a

[1, 2, 3, 4, 5, 6]>>>#区别连接操作>>> a=[1,2,3]>>> b=[4,5,6]>>> a+b

[1, 2, 3, 4, 5, 6]>>>a

[1, 2, 3]

4、index

index方法用于从列表中找出某一个匹配项的索引位置:

>>> knights=['we','are','the','knigths','who','say','ni']>>> knights.index('who')4

>>> knights=['we','are','the','knigths','who','say','ni']>>> knights.index('herring')Traceback (most recent call last):

File"<pyshell#184>", line 1, in <module>

knights.index('herring')

ValueError: 'herring' is not in list

没有成功找到会引发异常

5、insert

insert方法用于将对象插入到列表中:

>>> numbers=[1,2,3,5,6,7]>>> numbers.insert(3,'four')>>>numbers

[1, 2, 3,'four', 5, 6, 7]>>>#extend方法一样,insert方法的操作也可以用分片赋值来实现>>> numbers=[1,2,3,5,6,7]>>> numbers[3:3]=['four']>>>numbers

[1, 2, 3,'four', 5, 6, 7]

6、pop

pop方法会移除列表中的一个元素(默认是最后一个),并且返回该元素的值:

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

>>>x

[1, 2]>>>x.pop(0)1

>>>x

[2]

注意:pop方法是唯一一个既能修改列表又返回元素值(除了None)的列表方法

7、remove

remove方法用于移除列表中某个值的第一个匹配项:

>>> x=['to','be','or','not','to','be']>>> x.remove('be')>>>x

['to','or','not','to','be']>>> x.remove('bee')Traceback (most recent call last):

File"<pyshell#19>", line 1, in <module>

x.remove('bee')

ValueError: list.remove(x): x not in list

8、reverse

reverse方法将列表中的元素反向存放,该方法也改变了列表但不返回值

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

[3, 2, 1]

9、sort

sort方法用于在原位置对列表进行排序,改变原来的列表,从而让其中的元素按照一定的

>>> x=[4,6,2,1,7,9]>>>x.sort()>>>x

[1, 2, 4, 6, 7, 9]

元组元组与列表一样,也是一种序列,唯一不同的是元组不可以修改:

任意对象的有序集合通过偏移存储属于不可变序列类型固定长度、异构、任意嵌套对象引用数组使用逗号分隔了一些值,就自动创建了一个元组:

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

()>>> 42

42

>>> 42,

(42,)>>> (42,)

(42,)

元组也是(大部分时候是)通过圆括号括起来的,空元组可以用没有包含内容的两个圆括号来表示:

tuple函数

tuple函数的功能和list函数基本上是一样的:以一个序列作为参数并把它转换为元组。

>>> tuple([1,2,3])

(1, 2, 3)>>> tuple('abc')

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

(1, 2, 3)

列表与元组的相互转化:

>>> T=('cc','aa','dd','bb')>>> tmp=list(T)>>>tmp

['cc','aa','dd','bb']>>> T=tuple(tmp)>>>T

('cc','aa','dd','bb')

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航